• c++全局函数 && 成员函数


     1 #include<iostream>
     2 using namespace std;
     3 class Test {
     4 public:
     5     Test(int a=0, int b=0)
     6     {
     7         this->a = a;
     8         this->b = b;
     9     }
    10     Test & add_menber(Test &t2)
    11     {
    12         this->a += t2.a;
    13         this->b += t2.b;
    14         return *this;
    15     }
    16     void printf(Test &t)
    17     {
    18         cout << "a="<<t.a << "b=" << t.b << endl;
    19     }
    20     ~Test()
    21     {
    22         
    23     }
    24 //private://全局函数如果不是友元函数不能访问私有属性
    25     int a;
    26     int b;
    27 
    28 };
    29 Test add(Test &t1, Test &t2)
    30 {
    31     Test temp;
    32     temp.a= t1.a + t2.a;
    33     temp.b = t1.b + t2.b;
    34     return  temp;
    35 }
    36 int main()
    37 {
    38     Test t1(1, 2), t2(3, 4), t3;
    39     t3 = add(t1, t2);
    40     cout << "t3.a="<<t3.a<<"t3.b="<<t3.b << endl;
    41 
    42     Test t4(100, 100),t5(200,200);
    43     t4.printf(t4.add_menber(t5));
    44     cout << "hello world!
    ";
    45     return 0;
    46 }

    summary:

    非静态成员函数有this指针,这样的成员函数实现参数会比全局函数少一个,反之全局函数参数会比非静态成员函数多一个。c++中多使用引用更好。

  • 相关阅读:
    IMYSQL-叶金荣
    mysql命令
    实效云计算用户组(ECUG) 与 阿里云
    GO 语言
    MYSQL 源代码编绎脚本
    MYSQL 源代码学习
    LINUX 性能工具使用
    CentOS 5.8 上安装 systemtap-2.6 转
    mysql php nginx
    redis 安装
  • 原文地址:https://www.cnblogs.com/yangguang-it/p/6418935.html
Copyright © 2020-2023  润新知