C++ friend 友元类——访问类中私有成员

tech2023-06-07  121

友元的目的:让一个函数或类 访问另一个类中私有成员

友元的三种实现:

全局函数做友元类做友元类成员函数做友元 #include <iostream> #include <string> using namespace std; //2.类做友元 class GoodFriend { public: Building *building; void visit() //参观函数 访问Building中的属性 { cout<<building->m_SittingRoom<<endl; cout<<building->m_BedRoom<<endl; } GoodFriend() { building=new Building; } }; //3.类成员函数做友元 class GoodGirlFriend { public: Building *building; void visit() //参观函数 访问Building中的属性 { cout<<building->m_SittingRoom<<endl; // cout<<building->m_BedRoom<<endl; //无法访问类的私有成员 } void visit2() { cout<<building->m_SittingRoom<<endl; cout<<building->m_SittingRoom<<endl; } GoodGirlFriend() { building=new Building; } }; class Building { //1.goodGay全局函数为Building的友元函数,可以访问Building中的私有成员 friend void goodGay(Building &building); //2.GoodFriend类为Building的友元类 friend class GoodFriend; //3.GoodGirlFrien类成员函数visit2做友元 friend void GoodGirlFriend::visit2(); public: Building() { m_SittingRoom="SittingRoom"; m_BedRoom="BedRoom"; } public: string m_SittingRoom; private: string m_BedRoom; }; //1.全局函数做友元 void goodGay(Building &building) { cout<<building.m_SittingRoom<<endl; cout<<building.m_BedRoom<<endl; } void func1() { Building building; goodGay(building); } void func2() { GoodFriend gf; gf.visit(); } void func3() { GoodGirlFriend ggf; ggf.visit(); ggf.visit2(); } int main() { func1(); func2(); func3(); return 0; }
最新回复(0)