C++中友元分为友元函数和友元类。友元提供了一种突破封装的方式,有时提供了便利。但是友元会增加耦合度,破坏了封装,所以友元不宜多用。
友元函数
使用场景
这里我们以日期类为例,想要实现日期类的流插入流提取运算符的重载,如果我们将运算符重载直接定义在类的内部,那么,在使用的时候会出现左运算符为this指针的情况,与正常情况不符,例如:
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
const Date* operator&()const
{
return this;
}
//不能使用成员函数
void operator<<(ostream& out)
{
out << _year << "-" << _month << "-" << _day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2022, 3, 24);
//cout << d1 << endl;//这种情况会报错,原因是左右操作数类型不一致
//d1.operator<<(cout);//运算符重载里面,如果是双操作数的运算符重载,第一个参数是左操作数,第二个参数是右操作数
//cout << d1 << endl;//自定义类型不支持直接使用流插入/流提取
d1 << cout;
return 0;
}