例子
当引用作为返回值的时候
class Person
{
public:
Person(int a) {
this->a = a;
}
//当引用作为返回值的时候
Person& add(Person &p){
this->a += p.a;
return *this;//this是指针,*this是指向的内存
}
public:
int a;
};
int main()
{
Person p(10);
Person p2(10);
p2.add(p).add(p);
cout << p2.a << endl;
system("pause");
return 0;
}
此时输出结果是 30
以值的方式返回
Person add(Person &p){
this->a += p.a;
return *this;
}
此时结果是 20
原因:
当函数返回一个引用时,返回的是对象本身
p2.add( p)返回值是p2本身
如果用值的方式返回是创建一个新的对象
p2.add( p)返回值是p2',此时p2.a = 20
p2.add( p).add( p) = p2'.add( p),与p2无关,所以最后p2.a=20