友元
概念
类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数
全局函数做友元
#include <iostream>
#include <string>
using namespace std;
class Building
{
friend void goodGay(Building &b); // 让全局函数goodGay作为本类的友元函数
public:
string m_SittingRoom;
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
private:
string m_BedRoom;
};
// 好基友 全局函数 可以访问客厅 也可以访问卧室
void goodGay(Building &b)
{
cout << "好基友正在访问:" << b.m_SittingRoom << endl;
cout << "好基友正在访问:" << b.m_BedRoom << endl;
}
// 普通朋友 只能访问客厅
void friend_(Building &b)
{
cout << "朋友正在访问:" << b.m_SittingRoom << endl;
// cout << "朋友正在访问:" << b.m_BedRoom << endl; // error: 'std::__cxx11::string Building::m_BedRoom' is private
}
int main()
{
Building b;
goodGay(b);
friend_(b);
return 0;
}
好基友正在访问:客厅
好基友正在访问:卧室
朋友正在访问:客厅
类做友元
#include <iostream>
#include <string>
using namespace std;
class Building;
class GoodGay
{
public:
GoodGay();
void visit();
Building *building;
};
class Building
{
friend class GoodGay; // 让GoodGay类成为友元
public:
string m_SittingRoom;
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
private:
string m_BedRoom;
};
GoodGay::GoodGay()
{
building = new Building;
}
void GoodGay::visit()
{
cout << "好基友类正在访问:" << building->m_SittingRoom << endl;
cout << "好基友类正在访问:" << building->m_BedRoom << endl;
}
int main()
{
GoodGay goodGay;
goodGay.visit();
return 0;
}
好基友类正在访问:客厅
好基友类正在访问:卧室
类中成员函数做友元
#include <iostream>
#include <string>
using namespace std;
class Building;
class GoodGay
{
public:
GoodGay();
void visit();
Building *building;
void visit2();
};
class Building
{
friend void GoodGay::visit(); // 让GoodGay类中的 visit函数 成为友元
public:
string m_SittingRoom;
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
private:
string m_BedRoom;
};
GoodGay::GoodGay()
{
building = new Building;
}
void GoodGay::visit()
{
cout << "好基友类正在访问:" << building->m_SittingRoom << endl;
cout << "好基友类正在访问:" << building->m_BedRoom << endl;
}
void GoodGay::visit2()
{
cout << "好基友类正在访问:" << building->m_SittingRoom << endl;
cout << "好基友类正在访问:" << building->m_BedRoom << endl;
}
int main()
{
GoodGay goodGay;
goodGay.visit(); // 只有visit可以访问
goodGay.visit2(); // error
return 0;
}