家长访问孩子

时间:2018-05-08 18:25:28

标签: c++ c++11

我理解陈述here的所有内容,它描述了Child如何访问父成员。但是,父母访问孩子怎么样?我只是无法理解这一点。为什么这是错的?您能否在编译期间根据静态绑定规则进行解释?这里学生班本身就受到了保护我想,但为什么呢?

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;
}

C-T错误:

  

错误是:输入:从“学生*”到“人员*”的转换存在,但无法访问

1 个答案:

答案 0 :(得分:3)

不是Person""" Student,关于继承的访问控制意味着什么

当您说class Student: public Person时,这意味着您宣布StudentPerson给每个人,这意味着main()知道Student*可以是由Person*引用。所以一切都很好。

当您说class Student: private Person时,表示Student继承了Person的功能,但这只是一个实现细节。这并不能让任何人知道StudentPerson所以它不能被视为一个main()。因此Student*认为Person*class Student: protected Person无关。

当你说Person时,它有点棘手,但这个过程仍然适用。您继承了Student的功能,Freshman的任何派生类也知道这一点。因此,如果您有一个继承自Student的{​​{1}}类,则它知道它也是Person。但是,这是特定于继承的类,main()不知道StudentPerson,因为该知识受到保护。