C++中的友元

友元的功能是让一个函数或者类,能够访问另一个类中的私有成员。

实现方法:

1.全局函数作为友元:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
using namespace std;
#include<string>

class Building{//类
friend void goodfri(Building *building);//这句话就是让全局函数做Building类的友元
//这样,private的m_bedroom才可以被goodfri访问
public:
Buliding(){//构造函数
this->m_sittingroom="keting";//在其中赋值
this->m_bedroom="woshi";
}
public:
string m_sittingroom;
private:
string m_bedroom;
};

void goodfri(Building *building){//全局函数
cout<<"now is:"<<building->m_sittingroom<<endl;
cout<<"now is:"<<building->m_bedroom<<endl;
}

void test01(){
Building b;//创建一个Building型的b
goodfri(&b);
}
int main(){
test01();
return 0;
}

2.类做友元:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<iostream>
using namespace std;
#include<string>

class Building;//提前声明一下有Building这个类
class goodfri{
public:
goodfri();//构造函数
void visit();//一个普通函数
private:
Building *building;//一个Building类型的指针
};

class Building{
friend class goodfri;//这句话就实现了类做友元,告诉Building,goodfri类是你的朋友(友元)
public:
Building();//构造函数
public:
string m_sittingroom;
private:
string m_bedroom;
};

Building::Building(){ //在类外面写构造函数
this->m_sittingroom="keting";
this->m_bedroom="woshi";
}

goodfri::goodfri(){//在类外面写构造函数
building=new Building;//创建了一个新的对象,new返回的是这个新的对象的地址,所以用指针来接收
//building指针是在goodfri中的private类型
}

void goodfri::visit(){
cout<<"now in:"<<building->m_bedroom<<endl;
cout<<"now in:"<<building->m_sittingroom<<endl;
}

void test01(){
goodfri hfri;//创建了一个goodfri类型的对象hfri
hfri.visit();
}

int main(){
test01();
system("pause");
return 0;
}

3.成员函数作为友元:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<iostream>
using namespace std;
#include<string>
class Building;
class goodfri{
public:
goodfri();//构造函数
void visit();
void visit2();//只是用来和visit函数做对比的
private:
Building *building;
};

class Building{
friend void goodfri::visit();//这句话就是让成员函数visit为友元

public:
Building();
public:
string m_sittingroom;
private:
string m_bedroom;
};

Building::Building(){
this->m_bedroom="woshi";
this->m_sittingroom="keting";
}

goodfri::goodfri(){
building=new Building;
}
void goodfri::visit(){
cout<<"now is:"<<building->m_sittingroom<<endl;
cout<<"now is:"<<building->m_bedroom<<endl;
}
void goodfri::visit2(){
cout<<"now is:"<<building->m_sittingroom<<endl;
//cout<<"now is:"<<building->m_bedroom<<endl;这句话不能访问,
}
void test01(){
goodfri hhh;
hhh.visit();
}
int main(){
test01();
system("pause");
return 0;
}