友元函数
全局函数做友元函数
友元函数目的是访问类中的私有成员属性
格式:
friend type 函数名 (参数...);
在类中加入 friend 函数声明
例:
class Building {
//void goodGay(Building* building)函数声明
friend void goodGay(Building* building);
public:
Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
public:
string m_SittingRoom;//客厅
private:
string m_BedRoom;//卧室
};
//友元函数
void goodGay(Building* building)
{
cout<<building->m_SittingRoom<<endl;
cout<<building->m_BedRoom<<endl;
}
成员函数做友元函数
例:
class Building;
class goodGay
{
public:
goodGay();
void visit();
private:
Building* building;
};
class Building {
//友元成员函数
friend void goodGay::visit();
public:
Building();
public:
string m_SittingRoom;//客厅
private:
string m_BedRoom;//卧室
};
goodGay::goodGay()
{
building = new Building;
}
//构造
Building::Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
void goodGay::visit()
{
cout << this->building->m_SittingRoom << endl;
cout << this->building->m_BedRoom << endl;
}
友元类
格式:
在类中加入友元类声明
friend class classname;
例:
class Building;
class goodGay
{
public:
goodGay();
void visit();
private:
Building* building;
};
class Building {
//友元类
friend class goodGay;
public:
Building();
public:
string m_SittingRoom;//客厅
private:
string m_BedRoom;//卧室
};
goodGay::goodGay()
{
building = new Building;
}
//构造
Building::Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
void goodGay::visit()
{
cout << this->building->m_SittingRoom << endl;
cout << this->building->m_BedRoom << endl;
}