#include <iostream>
#include <cstring>
using namespace std;
class Test{
public:
Test(int a,int b){
this->m_a=a;
this->m_b=b;
}
void print(){
cout<<"m_a: "<<this->m_a<<" m_b: "<<this->m_b<<endl;
}
//+
Test TestAdd(Test &t){
Test temp(this->m_a+t.m_a,this->m_b+t.m_b);
return temp;
}
//+=
void TestAdd2(Test &t){
this->m_a+=t.m_a;
this->m_b+=t.m_b;
}
//+= 返回本身
Test& TestAdd3(Test &t){
this->m_a+=t.m_a;
this->m_b+=t.m_b;
return *this;//返回对象的本身
}
private:
int m_a;
int m_b;
};
int main(){
Test t1(10,20);
Test t2(100,200);
Test t3 = t1.TestAdd(t2);
t3.print();
cout<<"---------------------------"<<endl;
//想对一个对象连续调用成员方法且每次改变对象本身,成员方法需返回引用
t1.TestAdd3(t2).TestAdd3(t1);
t1.print();
system("pause");
return 0;
}
对象返回自身
最新推荐文章于 2023-07-27 15:39:28 发布