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++中多使用引用更好。

posted @ 2017-02-20 12:11  Crystal_Guang  阅读(2103)  评论(0编辑  收藏  举报