C++ 中的继承和友谊
在 C++ 中,友谊不可继承。这意味着,如果一个父类有一些友元函数,则子类将无法获得这些函数作为友元。
在此示例中,它将生成一个错误,因为 display() 函数是 MyBaseClass 的友元,但不是 MyDerivedClass 的友元。 display() 可以访问 MyBaseClass 的私有成员。
示例
#include <iostream> using namespace std; class MyBaseClass { protected: int x; public: MyBaseClass() { x = 20; } friend void display(); }; class MyDerivedClass : public MyBaseClass { private: int y; public: MyDerivedClass() { x = 40; } }; void display() { MyDerivedClass derived; cout << "The value of private member of Base class is: " << derived.x << endl; cout << "The value of private member of Derived class is: " << derived.y << endl; } main() { display(); }
输出
[Error] 'int MyDerivedClass::y' is private [Error] within this context
广告