4.4 友元
在程序中,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术。
友元的目的就是让一个函数或者类 访问另一个类中私有成员。
友元的关键字为 friend。
友元的三种实现:
- 全局函数做友元
- 类做友元
- 成员函数做友元
4.4.1 全局函数做友元
friend void bestFriend(Building* build);
示例:
#include<iostream>
#include<string>
using namespace std;
class Building {
//bestFriend全局函数是Building好朋友,可以访问Building中的私有成员
friend void bestFriend(Building* build);
public:
Building() {
this->sittingRoom = "客厅";
this->bedRoom = "卧室";
}
public:
string sittingRoom;
private:
string bedRoom;
};
//全局函数
void bestFriend(Building *build) {
cout << "my best friend in my " << build->sittingRoom << endl;
cout << "my best friend in my " << build->bedRoom << endl;//非友元时不能访问bedRoom
}
void test01() {
Building build1;
bestFriend(&build1);
}
int main() {
test01();
return 0;
}
4.4.2 类做友元
一、类做友元,访问本类中的私有成员
friend class bestFriend;
二、在类外实现成员函数
#include<iostream>
#include<string>
using namespace std;
class Building; //先声明一下这个类,告诉系统等下写这个类
class bestFriend {
public:
bestFriend();
void visit();//参观函数,访问Building中的属性
private:
Building* buildings;//指针
};
class Building {
//类做友元,访问本类中私有成员
friend class bestFriend;
public:
Building();
string sitting_room;
private:
string bed_room;
};
//类外写成员函数
Building::Building() {
this->sitting_room = "客厅";
this->bed_room = "卧室";
}
bestFriend::bestFriend() {
//在堆区创建一个Building对象,让指针*buildings指向这个对象
buildings = new Building;
}
void bestFriend::visit() {
cout << "my bestfriend in my " << buildings->sitting_room << endl;
cout << "my bestfriend in my " << buildings->bed_room << endl;
}
void test01() {
bestFriend bf;
bf.visit();
}
int main() {
test01();
return 0;
}
4.4.3 成员函数做友元
friend void bestFriend::visit1();
示例:
#include<iostream>
#include<string>
using namespace std;
class Building;
class bestFriend {
public:
bestFriend();
void visit1();//让visit1() 可以访问Building中的私有成员
void visit2();//让visit2() 不可以访问Building中的私有成员
private:
Building *buildings;
};
class Building {
//成员函数做友元
//告诉编译器,bestFriend类下的visit1()成员函数作为本类的好友,可以访问本类的私有成员
friend void bestFriend::visit1();
public:
Building();
string sitting_room;
private:
string bed_room;
};
Building::Building() {
this->sitting_room = "sitting room";
this->bed_room = "bed room";
}
bestFriend::bestFriend() {
buildings = new Building;
}
void bestFriend::visit1() {
cout << "visit1 my best friend in my " << buildings->sitting_room << endl;
cout << "visit1 my best friend in my " << buildings->bed_room << endl;
}
void bestFriend::visit2() {
cout << "visit2 my best friend in my " << buildings->sitting_room << endl;
}
void test01() {
bestFriend bf;
bf.visit1();
bf.visit2();
}
int main() {
test01();
return 0;
}