C++语法小记---友元

友元函数
  • 延续C语言的结构体编程方式,直接访问类的私有成员,提高效率

  • 友元分为函数友元和类友元

    • 友元函数可以访问类的所有成员

    • 友元类的所有成员函数都是友元函数

  • 友元不具备传递性

  • 友元函数和类的成员函数的区别

    • 友元函数不是类的成员,只是声明

    • 成员函数有this指针,而友元函数没有this指针

  • 开发中不建议使用友元函数,破坏了类的封装性

 

函数友元例子

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Test
 6 {
 7 private:
 8     int a;
 9 
10 public:
11     Test() { a = 0;}
12     
13     Test(int a) {this->a = a;}
14 
15     void show()
16     {
17         cout << "a = " << a << endl;
18     }
19     
20     friend void g_show(Test t);
21 };
22 
23 void g_show(Test t)
24 {
25     cout << "[g_show] t.a = " << t.a << endl;
26     return;
27 }
28 
29 int main()
30 {
31     Test t(1);
32     t.show();
33     g_show(t);
34     return 0;
35 }

 

类友元例子

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Test
 6 {
 7 private:
 8     int a;
 9 
10 public:
11     Test() { a = 0;}
12     
13     Test(int a) {this->a = a;}
14     
15     friend class Friend;
16 };
17 
18 class Friend
19 {
20 private:
21     Test t;
22     
23 public:
24     Friend() : t(10) {}
25     
26     void show()
27     {
28         cout << "Friend t.a = " << t.a << endl;
29     }
30 };
31 
32 int main()
33 {
34     Friend f;
35     f.show();
36 
37     return 0;
38 }

 

posted @ 2019-08-03 10:24  Yong_无止境  阅读(159)  评论(0编辑  收藏  举报