首页 > 解决方案 > 继承和访问属性

问题描述

我正在学习 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;
}

这里的开发者类继承自雇员类,但是当我试图从主函数中打印开发者的名字时,cout << d.name << endl;我得到了这个错误'std::string Employee::name' is inaccessible within this context

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

标签: c++oopinheritance

解决方案


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

如果你改变这个:

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

对此:

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

默认情况下,类继承是“私有”继承,结构继承是“公共”继承。私有继承意味着基类的公共和受保护成员将被子类视为私有成员。

您可以通过在基类名称前显式写入 或public来覆盖此默认行为。privateprotected

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


推荐阅读