C++之友元

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 
 7 class Screen
 8 {
 9 public:
10     //类的友元函数,可以使用类中的私有成员变量
11     friend int calcArea(Screen &screen);
12     //友元类 ,也可以将类其中的一个函数设为友元
13     friend class Window_Mgr;
14 
15     typedef string::size_type index;
16     //构造函数并进行初始化
17     Screen(int ht=0,int wd=0):contents(ht*wd,' '),cursor(0),height(ht),width(wd){}
18     int area()const
19     {
20         return height*width;
21     }
22 
23 private:
24     string contents;
25     index cursor;
26     int height,width;
27 };
28 
29 //窗口管理类
30 class Window_Mgr
31 {
32 public:
33     void relocate(int r,int c,Screen &s)
34     {
35         s.height +=r;
36         s.width +=c;
37     }
38 };
39 
40 int calcArea(Screen &screen)
41 {
42     return screen.height*screen.width;
43 }
44 
45 int main()
46 {
47 
48     Screen a(60,100);
49     Window_Mgr w;
50     cout<<a.area()<<endl;
51     w.relocate(20,60,a);
52     cout<<calcArea(a)<<endl;
53     return 0;
54 }

 

posted @ 2020-04-05 20:44  萌萌~  阅读(162)  评论(0编辑  收藏  举报