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

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

环境: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>


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

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



  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值