全局函数VS成员函数

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class  Test
 6 {
 7 public:
 8     Test(int a, int b)
 9     {
10         this->a = a;
11         this->b = b;
12     }
13     int getA()
14     {
15         return a;
16     }
17     int getB()
18     {
19         return b;
20     }
21 
22     Test add(Test &t2)
23     {
24         this->a = this->a + t2.getA();
25         this->b = this->b + t2.getB();
26         //return *this;
27     }
28     void print()
29     {
30         cout << "a = " << a << "  b = " << b << endl;
31 
32     }
33 protected:
34 private:
35     int a, b;
36 };
37 
38 Test add(Test &t1, Test &t2)
39 {
40     Test t3(t1.getA() + t2.getA(), t1.getB() + t2.getB());
41     return t3;
42 }
43 
44 int main()
45 {
46     Test t1(1, 2);
47     Test t2(2, 3);
48     //Test t3 = add(t1, t2);
49     t1.add(t2);
50     t1.print();
51 
52     system("pause");
53     return 0;
54 }

 成员函数隐藏了一个this指针,谁调用成员函数,this指针就指向谁,这个this指针就是指向调用成员函数的对象的首地址.

在成员函数里, *this 就是调用对象元素本身.一般用于return *this

原文地址:https://www.cnblogs.com/c-slmax/p/5183854.html