c++ - 家长访问孩子
问题描述
我理解这里所说的一切,它描述了 Child 如何访问 Parent 成员。但是,父母访问孩子怎么样?我只是无法理解这一点。为什么是错的?您能否在编译时解释一下静态绑定规则?我猜这里学生类本身会受到保护,但为什么呢?
using namespace std;
class Person
{
public:
int b;
};
class Student : protected Person
{
public:
int c;
};
int main()
{
Student s;
Person *pPerson;
pPerson = &s;
return 0;
}
CT误差:
错误是:类型转换:从 'Student*' 到 'Person*' 的转换存在,但无法访问
解决方案
它不是关于如何Person
“看到” Student
,而是关于继承的访问控制意味着什么。
当你说class Student: public Person
时,这意味着你在向所有人宣布 aStudent
是 a Person
,这意味着main()
知道 aStudent*
可以被 a 引用Person*
。所以一切都很好。
当您说class Student: private Person
时,它意味着Student
从 继承功能Person
,但这只是一个实现细节。这不会让任何人知道 aStudent
是 aPerson
所以它不能被认为是一个。因此main()
认为Student*
和Person*
无关。
当您说时class Student: protected Person
,它有点棘手,但该过程仍然适用。您正在继承功能,Person
并且任何派生类Student
也知道这一点。所以如果你有一个Freshman
继承自的类Student
,它就会知道它也是一个Person
. 但是,这是特定于继承的类,main()
不知道Student
是Person
因为该知识受到保护。
推荐阅读
- python - 去除最远点的有效方法
- c# - API 调用:“端点 ... 包含授权元数据,但未找到支持授权的中间件。”
- python - python-pcl Segmentation_PointXYZI'对象没有属性'set_MaxIterations'
- python - 如何制作可滚动的滚动条?
- excel - VBA - 如何在另一个工作表中超链接多个单元格
- embedded-linux - Linux串口控制台输入,framebuffer控制台输出
- php - CURL PHP 对象引用未设置为对象的实例
- javascript - 第二个for循环输出4怎么样。不应该是3吗?
- flutter - 图像宽度,高度未调整到颤振中的参数
- julia - 错误:LoadError:UndefVarError:类型未定义