全局函数和成员函数
- 把全局函数转化成成员函数,通过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+a
printf ("c = %d\n",c);
return 0;
}