代码中函数test()返回值如果是引用,输出结果为64,但如果返回的是对象本身,为什么返回值就是46了呢?
请大佬帮忙指点一下!
#include <iostream>
using namespace std;
class Person
{
public:
int age;
Person(int age)
{
this->age = age;
}
Person& Age_add_age(const Person& p) //常量引用
{
this->age += p.age;
return *this;
} //这个函数返回值为 Person&时,最终输出为64;返回值为 Person时的输出为46???
};
//返回对象本身用return *this
void test()
{
Person p1(18);
Person p2(10);
p2.Age_add_age(p1); //此时p2.age为28
cout << "p2的年龄为:" << p2.age << endl;
p2.Age_add_age(p1).Age_add_age(p1); //Age_add_age()的返回值必须为一个对象才可以作为左值使用
cout << "p2的年龄为:" << p2.age << endl;
}
int main()
{
test();
system("pause");
return 0;
}
p2.Age_add_age(p1).Age_add_age(p1);
如果返回对象,那么上述代码执行完p2.Age_add_age(p1)后,返回一个匿名对象p,接着执行p.Age_add_age(p1)
应该是返回对象的时候又发生一次拷贝,调用了拷贝构造函数,返回当前对象的引用就不会拷贝