为什么要有友元?
一个全局函数或者类想访问另一个类私有的成员属性的时候,就要用到友元
关键词:friend
使用友元的三种情况
1.全局函数做友元
告诉我想访问的那个类,我是你们这个类的我的好朋友,可以让我访问私有成员属性
#include <iostream> using namespace std; class Building { friend void GoodFreind(Building& b); string bedroom;//私有的 public: string sittingroom; Building();//类内声明构造函数 /*{ this->bedroom = "卧室"; this->sittingroom = "客厅"; }*/ }; Building::Building() { this->bedroom = "卧室"; this->sittingroom = "客厅"; } void GoodFreind(Building& b) {//当全局函数想访问一个类中的私有成员属性的时候,把这个函数声明成友元函数就可以实现了 cout << "朋友相进入" << b.sittingroom << endl; cout << "朋友想进入" << b.bedroom << endl; } int main() { Building b; GoodFreind(b); return 0; }
2.类做友元
#include <iostream> using namespace std; class Building { friend Friend;//Friend类设为友元 string bedroom;//私有的 public: string sittingroom; Building();//类内声明构造函数 }; class Friend { Building *b; public: Friend();//类内声明构造函数 ~Friend(); void vist(); }; Building::Building() { this->bedroom = "卧室"; this->sittingroom = "客厅"; } Friend::Friend(){ b = new Building();//成员变量指向堆区空间了,要调用析构函数 } Friend::~Friend() { if(b) delete b; } void Friend::vist() {//一个类想访问另一个类的私有成员,把这个类变为友元 cout << "朋友想进入" << b->sittingroom; cout << "朋友想进入" << b->bedroom; } int main() { Building b; return 0; }
3.类中的成员函数做友元
#include <iostream> using namespace std; class Friend { Building* b; public: Friend();//类内声明构造函数 ~Friend(); void vist(); }; class Building { friend void Friend::vist();//Friend类里面的成员函数设为友元 string bedroom;//私有的 public: string sittingroom; Building();//类内声明构造函数 }; Building::Building() { this->bedroom = "卧室"; this->sittingroom = "客厅"; } Friend::Friend(){ b = new Building();//成员变量指向堆区空间了,要调用析构函数 } Friend::~Friend() { if(b) delete b; } void Friend::vist() {//一个类想访问另一个类的私有成员,把这个类变为友元 cout << "朋友想进入" << b->sittingroom; cout << "朋友想进入" << b->bedroom; } int main() { Building b; return 0; }