先思考一个问题,如何将不属于当前结构的函数访问当前结构中的成员?
在这里就引出了友元这个概念。在当前结构中声明结构外函数为友元函数,则该友元函数就可访问该结构中的所有成员。
友元又分为:友元函数和友元类。
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;
}
上述代码可正常运行。、
但运算符重载时,需考虑到,不改变运算符本身的含义。<<
是可对结果进行连续输出的,所以上述代码无法进行连续输出,因为没有返回值类型。
做修改:返回输出流的引用
友元函数需要注意的点:
- 尽量不要用
const
修饰友元函数。在返回值为引用时,就会出错。 - 友元函数可在类中的任何地方声明,不受类的访问限定符限制
- 一个函数可以是多个类的友元函数
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();
}
正常输出结果:
友元类中的注意事项:
- 友元关系是单向的,不具有交换性。B是A的友元,A未在B中friend,则A不是B的友元。
- 友元关系不能传递。B是A的友元,C是B的友元,C不一定是A的友元。