在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