1.概念:
友元提供了一种突破封装的方式,有时提供了便利。但是友元会增加耦合度,破坏了封装,所以友元不宜多用。
2.友元分类:
友元函数和友元类
(1)友元函数:
友元函数可以直接访问类的私有成员,它是定义在类外部的普通函数,不属于任何类,但需要在类内部声明,声明时需要加friend关键字。
#include <iostream>
using namespace std;
class Date
{
//友元声明
friend ostream& operator<<(ostream& _cout,const Date& d);
friend istream& operator>>(istream& _cin,Date& d);
public:
Date(int year = 1900, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
}
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& _cout,const Date& d)
{
_cout << d._year << "-" << d._month << "-"<<d._day;
return _cout;
}
istream& operator>>(istream& _cin,Date& d)
{
_cin >> d._year;
_cin >> d._month;
_cin >> d._day;
return _cin;
}
int main()
{
Date d;
cin >> d;
cout << d << endl;
return 0;
}
(2)友元类:
友元类的所有成员函数都可以是另一个类(Time)的友元函数,都可以访问另一个类(time)的非公有成员。
class Time
{
friend class Date;
public:
Time(int hour = 0, int minute = 0, int second = 0)
:_hour(hour)
, _minute(minute)
, _second(second)
{
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
//友元声明
friend ostream& operator<<(ostream& _cout, const Date& d);
friend istream& operator>>(istream& _cin, Date& d);
public:
Date(int year = 1900, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
}
void SetTimeOfDate(int hour,int minute,int second)
{
_t._hour=hour;
}
private:
int _year;
int _month;
int _day;
Time _t
};
3.友元特点:
友元函数特点:
(1)友元函数可以访问类的私有和保护成员,但不是类的成员函数
(2)友元函数不能用const修饰
(3)友元函数可以在类定义的任何地方声明,不受类访问限定限制
(4)一个函数可以是多个类的友元函数
(5)友元函数的调用与普通函数的调用原理相同
友元类特点:
(1)友元关系是单向的,不具有交换性。
(2)友元关系不能传递
(3)友元关系不能继承