c++之友元
发布时间:2020-12-16 09:06:15 所属栏目:百科 来源:网络整理
导读:客厅:客人可以随意走动;卧室:只有自己能进去; 现在想要自己的好朋友可以进去,就需要用到友元技术。即友元的目的就是让一个函数或者类访问另一个类中私有成员。 关键字:friend 三种实现方法: 全局函数做友元 类做友元 成员函数做友元 全局函数做友元:
客厅:客人可以随意走动;卧室:只有自己能进去; 现在想要自己的好朋友可以进去,就需要用到友元技术。即友元的目的就是让一个函数或者类访问另一个类中私有成员。 关键字:friend 三种实现方法:
全局函数做友元: #include<iostream> using namespace std; class Building{ friend void goodGay(Building* building); public: Building() { room = "客厅"; myRoom = 卧室; } : string room; private myRoom; }; //全局函数 void goodGay(Building *building) { cout << 好朋友正在访问" <<building->room<< endl; 如果不将dooGay变成Building的友元函数,这里就会报错 cout << "好朋友正在访问" << building->myRoom << endl; } void test() { Building building; goodGay(&building); } int main() { test(); system(pause); return 0; } 类做友元: 说明:在类外定义成员函数时,需要先在类中声明函数。利用类名::函数名(),可以定义类的成员函数。 #include<iostream> std; Building{ friend class GoodGay; room; Building(); 类外写成员函数 Building::Building() { room = ; myRoom = ; } GoodGay { : Building* building; GoodGay(); visit(); }; GoodGay::GoodGay() { building = new Building(); } GoodGay::visit() { cout << 好基友类正在访问:" << building->room << endl; cout << "好基友类正在访问:" << building->myRoom << test() { GoodGay gg; gg.visit(); } 成员函数做友元: |