【发布时间】: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 << d.name << 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 <bits/stdc++.h>的可怜网站学习C++,向books written by professionals学习。 -
“无需重新分配”,您也可以(并且更喜欢)与其他成员一起这样做:
Employee(string N, int a, int w) : name(N), age(a), weight(w) {} -
非常感谢@UnholySheep
-
@Evg 好的先生,,,,,
标签: c++ oop inheritance