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!\n";
45     return 0;
46 }

summary:

非静态成员函数有this指针,这样的成员函数实现参数会比全局函数少一个,反之全局函数参数会比非静态成员函数多一个。c++中多使用引用更好。
原文链接: https://www.cnblogs.com/yangguang-it/p/6418935.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/249629

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午3:50
下一篇 2023年2月14日 上午3:50

相关推荐