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 生日广州男生祝福语简短