zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    AliSQL的编译使用
    linux下编译gcc6.2.0
    TransmitFile函数的简单使用
    C++11的简单线程池代码阅读
    TJpgDec使用说明
    TJpgDec—轻量级JPEG解码器
    PPM图片格式及其C读写代码
    linux下vmware的安装、物理分区使用及卸载
    visual stuido 跨解决方案调试
    Proj.4坐标系统创建参数
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11293947.html
Copyright © 2011-2022 走看看