【C++】友元(含内部类)
一、友元是什么
我把你添加为我的友元,那么你可以访问我的成员。特别注意:它是单向的。即,我把你添加为我的友元,我却不能访问你的成员,除非你把我添加为你的友元。
以下代码可以让你粗略了解友元的使用。
#include<iostream>
using namespace std;class Date
{
//设置友元friend ostream& operator<< (ostream& cout, const Date& d);public:// 获取某年某月的天数int GetMonthDay(int year, int month){int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){days[2] = 29;}return days[month];// 全缺省的构造函数Date(int year = 1900, int month = 1, int day = 1){_year = year;_month = month;_day = day;if (month < 1 || month > 12 || day < 1 || day > GetMonthDay(year, month)){cout << "非法日期" << endl;}}// 拷贝构造函数// d2(d1)Date(const Date& d){_year = d._year;_month = d._month;_day = d._day;}// 赋值运算符重载// d2 = d3 -> d2.operator=(&d2, d3)Date& operator=(const Date& d){_year = d._year;_month = d._month;_day = d._day;return *this;}// 析构函数~Date(){;}private:int _year;int _month;int _day;};//运算符重载
ostream& operator<< (ostream& cout, const Date& d)
{cout << d._year << "年" << d._month << "月" << d._day << "日" << endl;return cout;
}
二、友元——友元函数/友元类
关于友元,我们要注意以下几点:
友元函数可访问类的私有和保护成员,但不是类的成员函数
友元函数不能使用const修饰
友元函数可以在类定义的任何地方声明,不受访问限定符(public/private/protected)限制
一个函数可以是多个类的友元函数
友元函数的调用与普通函数的调用原理相同
三、内部类
内部类天生就是外部类的友元
BB类受AA类域和访问限定符的限制,它们是两个独立的类
class AA
{
public:class BB{public:void FuncBB(){AA aa;aa._a = 1;}private:int _b;};private:int _a;
};int main()
{cout << sizeof(AA) << endl;AA aa;//创建BB类的对象bb1AA::BB bb1;//const引用会延长匿名对象生命周期//ref出了作用域,匿名对象就销毁了const AA& ref = AA();return 0;
}