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
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短