C++ 中的friend 函数的解释

在C++中,有时会见到用到friend这个关键字来生成friend class 或者 friend function, 小编翻了中文材料,这个friend 翻译成友元,随之就是友元函数或者友元类。现在,小编就为大家来解释一下和如何怎么用这个friend。由于,小编看的是英文教材,所以,会用英文来描述什么是friend和应该如何使用。

Remember that with data hiding and encapsulation, we force clients to manipulate private data through public member functions. By declaring friends, we allow non-member functions or member functions of other classes access to private data.
A class can declare another class to be a friend.
When we do this, the first class gives all member functions of the second class permission to access all of its protected and private information (not the other way around; a class cannot declare itself a friend of another class).

下面这一段话对怎么来实现这个friend有解释:
By declaring an entire class as a friend, all members of the friend class have permission to access the protected and private members of the declaring class. This grants special privileges to the friend class’ member functions. However, declaring a class to be a friend does not grant any privileges to functions that may be called by member functions of the friend class.
举列子:
class declaring_class{
friend class class_name1;
};

如果还是不明白这上面几段英文讲什么,那么小编就直接上代码:

//This don't include the inheritance concepts
#include<iostream>

using namespace std;

//A class likes the declaring class
class A
{
	public:
		A()
		{
			a = 0;
		}
		friend class B;

	private:
		int a;
};

class B
{
	public:
		void intro(A & x)
		{
			cout<<"This is the B class."<<endl;
			cout<<"This function calls the A class data member."<<endl;
			cout<<"a = "<<x.a<<endl;
		}
};

int main()
{
	A a;
	B b;
	b.intro(a);
	cout<<endl;
	return 0;
}

结果展示:

如果要将friend 这个方法应用到inheritance(继承)里,那如何将上面的代码改动一下呢?关于什么是继承,小编就不在这里解释了。大家就可以上网搜资料,下面,小编用的public derivation来表示继承。
代码展示:

//在继承体系里使用friend
#include<iostream>

using namespace std;

class A
{
	public:
		A()
		{
			a = 0;
		}
	
		friend class B;

	private:
		int a;
};

class B : public A
{
	public:
		void intro()
		{
			cout<<"This is the B class."<<endl;
			cout<<"a = "<<a<<endl;
		}
};

int main()
{
	B b;
	b.intro();
	cout<<endl;
	return 0;
}

这段代码跑出的结果同样跟上面的结果是一样的。

有可能会有人问,如果我将声明的friend 放在declaring_class的private里面,还能不能跑呢?答案是肯定的. 因为小编在上面已经介绍了,
By declaring an entire class as a friend, all members of the friend class have permission to access the protected and private members of the declaring class. This grants special privileges to the friend class’ member functions.

希望这篇文章对大家的学习有所帮助!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值