1、全局函数做友元
#include <iostream>
using namespace std;
#include <string>//建筑物类
class Building {//goodGay全局函数是 Building好朋友 可以访问Building中私有成员friend void goodGay(Building* building);public:Building() {m_SittingRoom = "客厅";m_BedRoom = "卧室";}string m_SittingRoom;//客厅private:string m_BedRoom;//卧室};//全局函数
void goodGay(Building* building) {cout << "好基友全局函数 正在访问:" << building->m_SittingRoom << endl;cout << "好基友全局函数 正在访问:" << building->m_BedRoom << endl;}void test01() {Building building;goodGay(&building);
}int main() {test01();system("pause");return 0;
}
2、类做友元
#include <iostream>
using namespace std;
#include <string>//类做友元
class Building;class GoodGay {public:GoodGay();void visit();//参观函数 访问Building中的属性Building * building;
};class Building {//GoodGay类是本类的好朋友 可以访问本类中私有成员friend class GoodGay;
public:Building();string m_SittingRoom;private:string m_BedRoom;
};//类外写成员函数
Building::Building() {m_SittingRoom = "客厅";m_BedRoom = "卧室";
}GoodGay::GoodGay() {//创建建筑物对象building = new Building;
}void GoodGay::visit() {cout << "好基友类正在访问:" << building->m_SittingRoom << endl;cout << "好基友类正在访问:" << building->m_BedRoom << endl;}void test01() {GoodGay gg;gg.visit();
}int main() {test01();system("pause");return 0;
}
3、成员函数做友元
#include <iostream>
using namespace std;
#include <string>class Building;class GoodGay {public:GoodGay();void visit();// 访问Building中私有成员void visit2();// 不可以访问Building中私有成员Building * building;
};class Building {//告诉编译器 GoodGay类下的visit成员函数作为本类的好朋友,可以访问私有成员friend void GoodGay::visit();public:Building();string m_SittingRoom;private:string m_BedRoom;
};//类外写成员函数
Building::Building() {m_SittingRoom = "客厅";m_BedRoom = "卧室";
}GoodGay::GoodGay() {//创建建筑物对象building = new Building;
}void GoodGay::visit() {cout << "visit 函数正在访问:" << building->m_SittingRoom << endl;cout << "visit 函数正在访问:" << building->m_BedRoom << endl;}
void GoodGay::visit2() {cout << "visit2 函数正在访问:" << building->m_SittingRoom << endl;//cout << "visit 函数正在访问:" << building->m_BedRoom << endl;}void test01() {GoodGay gg;gg.visit();gg.visit2();
}int main() {test01();system("pause");return 0;
}