geeksforgeeks-043-继承和友元关系

如果基类有一个友元函数,那么这个函数不会变成派生类的友元函数。
如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

class A
{
protected:
int x;
public:
A() { x = 0;}
friend void ();
};

class B: public A
{
public:
B() : y (0) {}
private:
int y;
};

void ()
{
B b;
cout << "The default value of A::x = " << b.x;


cout << "The default value of B::y = " << b.y;
}

int main()
{
show();
getchar();
return 0;
}

以上程序输出错误,因为show是基类A的友元,但是却想访问派生类B的private变量。

派生类的友元函数可以正常访问基类成员。