• 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 }
  • 相关阅读:
    JavaScript获取http,http://请求协议头,域名,端口,url
    JAVA Pattern正则获取大括号中内容,substring字符串截取获取大括号中内容
    系统时间相关
    简单搭建nfs
    电信电话相关
    windows常用设置
    sort用法
    vim查询替换相关
    vim常用命令 技巧
    编绎vim8.2+deepin v15.11
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11293947.html
Copyright © 2020-2023  润新知