【C++】友元的理解和使用

先思考一个问题,如何将不属于当前结构的函数访问当前结构中的成员?

在这里就引出了友元这个概念。在当前结构中声明结构外函数为友元函数,则该友元函数就可访问该结构中的所有成员。

友元又分为:友元函数友元类

1.友元函数

友元函数可访问类中的所有成员,但不是该类中的成员函数

例:

class Date
{
	friend void Print(Date& d);//友元函数
public:
	Date(int year, int month, int day)//构造函数
		: _year(year)
		, _month(month)
		, _day(day)
	{}
private:
	int _year;
	int _month;
	int _day;
};

void Print(Date& d)//外部函数
{
	cout << d._year << "-" << d._month << "-" << d._day << endl;
}

void TestClass()
{
	Date d1(2020,10,6);
	Date d2(2020, 10, 1);
	Print(d1);
}

结果:类外函数可访问类中的成员
在这里插入图片描述

1.1 如何对<< 和 >>进行重载呢?

若在类中对<<进行重载:
在这里插入图片描述
而将程序改成这样:可正常运行
在这里插入图片描述
结果为:
在这里插入图片描述
为什么会这样呢?

成员函数中,默认的第一个参数为this指针。则this指针需要作为重载符的左操作数。而在上述中,cout作为了左操作数。但这也不符合<<本身的定义,所以是不对的。则必须将该函数进行类外声明和实现,但是类外的函数又没办法访问类中成员,这里就要采用友元函数对<<进行重载。

class Date
{
	friend void Print(Date& d);//友元函数
	friend void operator<<(ostream& _cout, Date& d);
public:
	Date(int year, int month, int day)//构造函数
		: _year(year)
		, _month(month)
		, _day(day)
	{}
private:
	int _year;
	int _month;
	int _day;
};

void operator<<(ostream& _cout,Date& d)
{
	_cout << d._year << "-" << d._month << "-" << d._day;
}

void TestClass()
{
	Date d1(2020,10,6);
	Date d2(2020, 10, 1);
	cout << d1;
}

上述代码可正常运行。、

但运算符重载时,需考虑到,不改变运算符本身的含义。<<是可对结果进行连续输出的,所以上述代码无法进行连续输出,因为没有返回值类型。

做修改:返回输出流的引用
在这里插入图片描述

友元函数需要注意的点:

  1. 尽量不要用const修饰友元函数。在返回值为引用时,就会出错。
  2. 友元函数可在类中的任何地方声明,不受类的访问限定符限制
  3. 一个函数可以是多个类的友元函数

 
 

2.友元类

友元类的所有成员函数都可以是另一个类的友元函数,都可以访问另一个类中的非公有成员。

例:B类是A类的友元类。

class Time
{
	friend class Date;
public:
	Time(int hour = 20, int mintue = 10, int second = 10)
		:_hour(hour)
		, _minute(mintue)
		, _second(second)
	{}
	void Print()
	{
		cout << _hour << "-" << _minute << "-" << _second << endl;
	}
private:
	int _hour;
	int _minute;
	int _second;
};

class Date
{
public:
	Date(int year, int month, int day)//构造函数
		: _year(year)
		, _month(month)
		, _day(day)
	{}
	void SetTime(int hour, int minute, int second)
	{
		_t._hour = hour;//调用Time类的成员变量
		_t._minute = minute;
		_t._second = second;
	}
	void Print()
	{
		_t.Print();//调用Time类的成员函数
	}
private:
	int _year;
	int _month;
	int _day;
	Time _t;
};


void TestClass()
{
	Date d1(2020,10,6);
	Date d2(2020, 10, 1);
	d1.SetTime(21, 13, 5);
	d1.Print();
}

正常输出结果:
在这里插入图片描述

友元类中的注意事项:

  1. 友元关系是单向的,不具有交换性。B是A的友元,A未在B中friend,则A不是B的友元。
  2. 友元关系不能传递。B是A的友元,C是B的友元,C不一定是A的友元。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值