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