[C++] 友元
原创
©著作权归作者所有:来自51CTO博客作者咸菜萝卜干的原创作品,请联系作者获取转载授权,否则将追究法律责任
全局函数作为友元
#include <iostream>
using namespace std;
#include <string>
class Building
{
friend void GoodGay(Building* building);
public:
Building()
{
m_sittingroom = "客厅";
m_bedroom = "卧室";
}
public:
string m_sittingroom;
private:
string m_bedroom;
};
void GoodGay(Building* building)
{
cout << "好基友正在访问:" << building->m_sittingroom << endl;
cout << "好基友正在访问:" << building->m_bedroom << endl;
}
int main()
{
Building building;
GoodGay(&building);
return 0;
}
类作为友元
#include <iostream>
using namespace std;
class Building;
class GoodGay
{
public:
GoodGay();
void visit();
Building * m_building;
};
class Building
{
friend class GoodGay;
public:
Building();
string m_sittingroom;
private:
string m_bedroom;
};
Building::Building()
{
this->m_sittingroom = "客厅";
this->m_bedroom = "卧室";
}
GoodGay::GoodGay()
{
this->m_building = new Building;
}
void GoodGay::visit()
{
cout << "好基友正在访问:" << this->m_building->m_sittingroom << endl;
cout << "好基友正在访问:" << this->m_building->m_bedroom << endl;
}
int main()
{
GoodGay gg;
gg.visit();
return 0;
}
成员函数作为友元
#include <iostream>
using namespace std;
class Building;
class GoodGay
{
public:
GoodGay();
void visit();
void visit2();
Building* m_building;
};
class Building
{
friend void GoodGay::visit2();
public:
Building();
string m_sittingroom;
private:
string m_bedroom;
};
Building::Building()
{
this->m_sittingroom = "客厅";
this->m_bedroom = "卧室";
}
GoodGay::GoodGay()
{
this->m_building = new Building;
}
void GoodGay::visit()
{
cout << "好基友正在访问:" << this->m_building->m_sittingroom << endl;
}
void GoodGay::visit2()
{
cout << "好基友正在访问:" << this->m_building->m_sittingroom << endl;
cout << "好基友正在访问:" << this->m_building->m_bedroom << endl;
}
int main()
{
GoodGay gg;
gg.visit2();
return 0;
}