友元
由于我们对成员变量都要进行封装,我们想要用封装后的成员变量时编译器就会报错,为了满足这一需求就产生了友元。
class A
{
friend class B;//友元标识
private:
int _a;
int _b;
};
class B
{
public:
void fun(const A&a)
{
cout << a._a << endl;
}
private:
int i;
};
B类就可以访问A类中的私有成员。
因为cout的输出流对象和隐含的this指针在抢占第一个参数的位置。this指针默认是第一个左操作数,而实际上cout需要的是第一个形参列表,所以我们将<<重载为全局函数,而全局函数无法访问类内成员变量,所以就需要定义operator <<为友元。
class Date
{
friend ostream& operator<<(ostream& _cout, const Date& d);
friend istream& operator>>(istream& _cin, Date& d);
public:
Date(int year, int month, int day):_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 << endl;
return _cout;
}
istream& operator>>(istream& _cin, Date& d)
{
_cin >> d._year;
_cin >> d._month;
_cin >> d._day;
}
内部类
内部类就是在一个类里面创建的类,如下代码B就是A的一个内部类,其天生就是A的友元而A不是B的友元
class A {
public:
class B {
public:
void fun(const A& a) {
cout << a.b << endl;
cout << _b << endl;
}
private:
int _b;
};
private:
int b;
};
//B是A的友元,A不是B的友元
int main() {
A a;
A::B b; //只能加访问限定符来访问B
b.fun(a);
return 0;
}