全局函數和成員函數
- 把全局函數轉化成成員函數,通過this指針隱藏左操作數
Test add(Test &t1, Test &t2)===》Test add(Test &t2)
- 把成員函數轉換成全局函數,多了一個參數
void printAB()===》void printAB(Test *pthis)
- 函數返回元素和返回引用
Test& add(Test &t2) //*this //函數返回引用{this->a = this->a + t2.getA();this->b = this->b + t2.getB();return *this; //*操作讓this指針回到元素狀態} Test add2(Test &t2) //*this //函數返回元素{//t3是局部變量Test t3(this->a+t2.getA(), this->b + t2.getB()) ;return t3;}
重要函數展示:
#include <stdio.h>class Test1_1
{
public:Test1_1 (int a){this->a = a;}void print(){printf ("a = %d\n", a);}// 將全局函數改成內部函數可以通過 this 隱藏左操作數int add(Test1_1 &b) //===> add(Test1_1 *const this, Test1_1 &b){return this->a+b.GetA();}int GetA(){return a;}
private:int a;
};int GetA(Test1_1 &obj)
{return obj.GetA();
}// 全局函數
int add(Test1_1 &a, Test1_1 &b)
{return a.GetA()+b.GetA();
}int main1_1()
{Test1_1 a(10), b(20);// int c = add(a, b);int c = a.add(b); // a+b b.add(a) ===> b+aprintf ("c = %d\n",c);return 0;
}