继承和访问属性

Inheritance and accessing attributes

我正在学习C++中的OOP,我写了这段代码来学习更多关于继承的知识。

#include<bits/stdc++.h>

using namespace std;

class Employee {
    public:  
    string name;
    int age;
    int weight;

    Employee(string N, int a, int w) {
        name = N;
        age = a;
        weight = w;
    }
};

// this means the class developer inherits from employee
class Developer:Employee {
    public:    
    string favproglang; //this is only with respect to developer employee
    
    // now we will have to declare the constructor
    Developer(string name, int age, int weight, string fpl)
    // this will make sure that there is no need to reassign the name, age and weight and it will be assigned by the parent class
    :Employee(name, age, weight) {
            favproglang = fpl;
    }

    void print_name() {
        cout << name << " is the name" << endl;
    }
};

int main() {
    Developer d = Developer("Hirak", 45, 56, "C++");

    cout << d.favproglang << endl;
    d.print_name();
    cout << d.name << endl; //this line gives error
    return 0;
}

此处开发人员 class 继承自员工 class,但是当我尝试从主函数 cout << d.name << endl; 打印开发人员姓名时出现此错误'std::string Employee::name' is inaccessible within this context.

我不明白为什么会出现此错误?我已在父 class 中将所有属性声明为 public。当我尝试从开发人员 class 本身访问 name 时,这个错误不是他们的,正如您在函数 print_help() 中看到的那样。此外,我还可以从主函数打印 d.favproglang,但为什么不打印 d.name?任何帮助将不胜感激。谢谢。

有 2 个解决方案(直接)。

解决方案 1

将员工和开发人员 class 的 class 关键字替换为关键字 struct。请注意,即使您将 Developer 的 class 关键字替换为 struct 并保留 Employee 的 class 关键字,这也将起作用。

解决方案 2

在派生列表中添加关键字public,如下一行所示:

class Developer:public Employee

这是因为继承的默认访问控制是“私有”。

如果你改变这个:

// this means the class developer inherits from employee
class Developer: Employee {

对此:

// this means the class developer inherits from employee
class Developer: public Employee {}

默认情况下,class继承是“private”继承,struct继承是“public”继承。私有继承意味着 public 并且基 class 的受保护成员将被子 class.

视为私有成员

您可以通过在基础 class 名称前显式写入 publicprivateprotected 来覆盖此默认行为。

搜索“c++ 基础 class 成员访问控制”以了解更多信息。