探索友元的继承和传递问题

书上说,友元类是单向的,不可继承,不可传递,为了验证它,我完成了以下的测试

环境:vs2013


一.友元类继承

1.A是B的友元类,A的public派生类能访问B的私有成员和保护成员吗?

不可以!请看下面代码:

<span style="font-size:18px;">class A;
class B
{
public:
	friend class A;
protected:
	int b1;
private:
	int b2;
};

class A
{
public:
	A() :a(10){};
	void fun1(B&x)
	{
		cout << x.b1 << " " << x.b2 << endl;
	}
private:
	int a;
};

class AA :public A
{
public:
	AA() :A(), aa(11){}
	void fun2(B&x)
	{
		cout << x.b1 << " " << x.b2 << endl;//编译器显示b1,b2不可访问
	}
private:
	int aa;
};</span>

2.A是B的友元类,A可以访问B的public派生类的私有成员和保护成员

不可以!请看下面代码:

<span style="font-size:18px;">class A;
class B
{
public:
	friend class A;
	B() :b(11){}
private:
	int b;
};

class BB :public B
{
public:
	BB() :B(), b1(22),b2(33){}
protected:
	int b1;
private:
	int b2;
};
class A
{
public:
	A() :a(10){};
	void fun1(B&x)
	{
		cout << x.b << endl;
	}
	void fun2(BB&y)
	{
		cout << y.b1 << " " << y.b2 << endl;//<span style="font-family: Arial, Helvetica, sans-serif;">编译器显示b1,b2不可访问</span>
	}
private:
	int a;
};</span>



二.友元类的传递

B是A的友元类,C是B的友元类,C可以访问A的私有成员和保护成员吗?

不可以!请看代码:

class A
{
public:
	friend class B;
protected:
	int a1;
private:
	int a2;
};

class B
{
public:
	friend class C;
protected:
	int b1;
private:
	int b2;
};

class C
{
public:
	void fun(A&x)
	{
		cout << x.a1 << " " << x.a2;//显示不可访问
	}
};


三.友元函数的继承

B是A的public派生类,A的友元函数可以访问B的私有成员和保护成员吗?

不可以!请看下面代码:

<span style="font-size:18px;">class A
{
	friend void fun(A&x, B&y);
protected:
	int a;
};
class B : public A
{
protected:
	int b;
};
void fun(A&x, B&y)
{
	cout << x.a << endl;//显示不可访问
	cout << y.b << endl;//显示不可访问
}</span>





四.友元函数的传递

B是A的友元类,B的友元函数可以访问A的私有成员和保护成员吗?

不可以!请看代码:

<span style="font-size:18px;">class A
{
public:
	friend class B;
protected:
	int a1;
private:
	int a2;
};

class B
{
	friend void fun(B&x, A&y);
public:
	B(int x=10)
	{
		b = x;
	}
private:
	int b;
};
void fun(B&x, A&y)
{
	cout << x.b << endl;//可以访问
	cout << y.a1 << " " << y.a2 << endl;//显示不可访问
}</span>


综上所得:友元类是单向的,不可继承,不可传递!!!

如有不同见解,欢迎指出,谢谢!!!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章