c++友元

4.4友元
作用:让某些函数或类能访问另一个类中的私有成员。
关键字 friend
友元的三种实现
1、全局函数做友元
2、类坐友元
3、成员函数做友元


--------------------------------------------------------

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 class GoodGay;//类声明
 6 class Building
 7 {
 8 
 9 public:
10 
11 Building()
12 {
13 m_BedRoom = "卧室";
14 m_SittingRoom = "客厅";
15 }
16 public:
17 string m_SittingRoom;//客厅
18 friend void GoodGay(Building* building);//全局函数作为友元
19 friend class GoodGay;//类做友元
20 friend GoodGay::GoodGay(string name);//成员函数做友元
21 private:
22 string m_BedRoom;//卧室
23 
24 };
25 class GoodGay
26 {
27 GoodGay(string name);
28 
29 private:
30 string m_Name;
31 
32 };
33 GoodGay::GoodGay(string name)//类内声明成员函数,类外实现类成员函数
34 {
35 
36 m_Name = name;
37 
38 }
39 
40 void GoodGay(Building *building)
41 {
42 cout << "好基友全局函数正在访问:" << building->m_SittingRoom << endl;
43 cout << "好基友全局函数正在访问:" << building->m_BedRoom << endl;
44 }
45 int main()
46 {
47 Building building;
48 GoodGay(&building);
49 return 0;
50 }

 

posted @ 2021-02-17 16:33  两天阿来  阅读(119)  评论(0)    收藏  举报