c++ 成员函数和全局函数的转换

来源:互联网 发布:淘宝订单数据跟踪 编辑:程序博客网 时间:2024/04/28 22:53
#include <iostream>using namespace std;class Test1{public:Test1(int a=0,int b=0){  this->a=a;this->b=b;}//成员函数Test1& t_add(Test1 &t2)    {this->a=this->a + t2.a;this->b=this->b + t2.b;return *this;    }int a;int b;protected:};Test1 t_add(Test1 &t1,Test1 &t2){Test1 t3;t3.a=t1.a+t2.a;t3.b=t1.b+t2.b;return t3;}void main(){//从成员函数转化为全局函数 只需要加一个this 指针(指向本类的this指针)//从全局函数转化为类的成员函数,需要减一个左操作数参数Test1 t1(1,2),t2(3,4);//Test1 t3=t_add(t1,t2);t1.t_add(t2);printf("%d  %d\n",t1.a,t2.b );system("pause");}

0 0