其他分享
首页 > 其他分享> > 类做友元

类做友元

作者:互联网

同时这里面还学会了类外定义成员函数

看代码吧

关键代码
friend class goodgay; 上面表示goodgay类是Building类的好友可以访问该类的私有成员
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 //类做友元
 5 class Building;
 6 class goodgay
 7 {
 8 
 9 public:
10     Building *building;
11 
12     void visit();//访问Building中的公有和私有属性
13 
14     goodgay();
15 };
16 class Building
17 {
18 friend class goodgay;
19 //上面表示goodgay类是Building类的好友可以访问该类的私有成员
20 public:
21     Building();
22 
23 public:
24     string sittingroom;
25 
26 private:
27     string bedroom;
28 };
29 
30 //类外写成员函数
31 Building::Building()
32 {
33     sittingroom = "sittingroom";
34     bedroom = "bedroom";
35 }
36 
37 goodgay::goodgay()
38 {
39     building = new Building;
40 }
41 
42 void goodgay::visit()
43 {
44     cout << "goodgay class is visiting " << building->sittingroom << endl;
45     cout << "goodgay class is visiting " << building->bedroom << endl;
46 }
47 
48 void test()
49 {
50     goodgay gg;
51     gg.visit();
52 }
53 
54 int main()
55 {
56     test();
57     return 0;
58 }

标签:友元,Building,sittingroom,public,bedroom,goodgay,class
来源: https://www.cnblogs.com/mch5201314/p/11587041.html