首页 > 解决方案 > 家长访问孩子

问题描述

我理解这里所说的一切,它描述了 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*' 的转换存在,但无法访问

标签: c++c++11

解决方案


它不是关于如何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()不知道StudentPerson因为该知识受到保护。


推荐阅读