【问题标题】:Inheritance and accessing attributes继承和访问属性
【发布时间】:2021-11-12 10:03:43
【问题描述】:

我正在学习 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 &lt;&lt; d.name &lt;&lt; endl; 打印开发者的名字时,我收到了这个错误'std::string Employee::name' is inaccessible within this context

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

【问题讨论】:

  • class Developer:Employee 使用 private 继承,你很可能想要class Developer: public Employee
  • 不要从教#include &lt;bits/stdc++.h&gt;的可怜网站学习C++,向books written by professionals学习。
  • “无需重新分配”,您也可以(并且更喜欢)与其他成员一起这样做:Employee(string N, int a, int w) : name(N), age(a), weight(w) {}
  • 非常感谢@UnholySheep
  • @Evg 好的先生,,,,,

标签: c++ oop inheritance


【解决方案1】:

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

如果你改变这个:

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

到这里:

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

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

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

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

【讨论】:

    【解决方案2】:

    对此有 2 个解决方案(直截了当)。

    解决方案 1

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

    解决方案 2

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

    class Developer:public Employee

    【讨论】:

      猜你喜欢
      • 2014-11-10
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 2019-03-08
      • 2019-10-21
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      相关资源
      最近更新 更多