c++继承(五)——基类与友元(了解)

    技术2023-06-23  68

    友元关系不能继承,也就是说基类友元不能访问子类私有和保护成员

    class Student; class Person { public: friend void fun(const Person& p, const Student& s); protected: int Ppro = 0; private: int Ppri = 1; }; class Student :public Person { protected: int Spro = 0; private: int Spri = 1; }; void fun(const Person& p, const Student& s) { cout << p.Ppri << " " << p.Ppro << endl; cout << s.Ppri << " " << s.Ppro << endl; //由于友元函数是不可被继承的,所以无法访问子类的保护和私有的成员 //cout << s.Spro << " " << s.Spri << endl; } int main() { Person p; Student s; fun(p, s); return 0; }

    这个知识点一般在我们的编写代码的时候是不会遇到的,作为了解就可以。

    Processed: 0.011, SQL: 9