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 好听的元旦简短祝福语