//全局函数和this指针函数 和函数返回元素,和函数返回引用的使用
#include<iostream>
using namespace std;
class test
{
private:
int a;
int b;
public:
test(int a=0,int b=0)
{
this->a =a;
this->b =b;
}
//t3=t1.testadd(t2);
test testadd(test &t2)
{
test tmp(this->a +t2.a ,this->b +t2.b );
return tmp;
}//t1.testadd2(t2) ;
//返回一个引用,相当于返回自身
//返回t1这个元素,this就是&t1
test & testadd2( test &t2)//如果想返回对象本身,不能用函数重载
{
this->a =this->a +t2.a ;
this->b =this->b +t2.b ;
return *this; //吧*(&t1) 又回到了 t1元素 ,操作让this指针回到元素状态
}
void print()
{
cout<<"a"<<a<<endl;
cout<<"b"<<b<<endl;
}
~test()
{
cout<<"析构函数"<<endl;
}
};
//全局函数的方法
test testadd(test &t1,test &t2)//会产生一个匿名对象,关于匿名对象具体性质,以前的博客有提到
{
test tmp;
return tmp;
}
int main01()
{
test t1(1,2);
test t2(3,4);
//思考,如何让t1+t2;
test t3 ;
//全局函数方法
t3=testadd(t1,t2);
//成员函数方法
//先把测试案例写出来,降低自己写代码的难度
//两种接匿名对象的方法:
test t4=t1.testadd(t2);//吧t1对象和t2对象相加,返回一个匿名对象,
t4.print() ; //然后用这个匿名对象等号给t3;匿名对象直接转化成t4;
test t5;
t5=t1.testadd(t2);//匿名对象复制给t5;
t5.print() ;
cout<<"hello"<<endl;
return 0;
}
//全局函数转成成员函数是少了一个参数。
//成员函数转成全局函数是多了一个参数。
int main()
{
test t1(1,2);
test t2(3,4);
//t1=t1+t2;
t1.testadd2(t2) ;
t1.print();
}