c++ - 继承和访问属性
问题描述
我正在学习 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
呢?任何帮助将不胜感激。谢谢你。
解决方案
这是因为继承的默认访问控制是“私有的”。
如果你改变这个:
// this means the class developer inherits from employee
class Developer: Employee {
对此:
// this means the class developer inherits from employee
class Developer: public Employee {}
默认情况下,类继承是“私有”继承,结构继承是“公共”继承。私有继承意味着基类的公共和受保护成员将被子类视为私有成员。
您可以通过在基类名称前显式写入 或public
来覆盖此默认行为。private
protected
搜索“c++ 基类成员访问控制”以了解更多信息。
推荐阅读
- java - 如何在运行模拟中获取对象的实例?
- python - 如何用撇号替换字符串中的双引号(不是指定它是字符串的外部双引号)
- assembly - 难以找到输入字符串
- regex - 如何用 RegExp 替换多个模式
- excel - 如何在 VBA 中命名文件
- android - HorizontalPager 中每个可组合页面一个 ViewModel
- javascript - 像 [1,3] 这样的数组给出错误“未捕获的语法错误:无效的解构赋值目标”
- php - 将用户重定向到 PHP Wordpress 中的目标页面
- postman - Postman API 调用返回 200 但消息“失败”
- authentication - passport-jwt 在每个请求上都返回 Unauthorized,JWTStrategy 中的代码没有执行