关于this指针的小问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 05:48:04
#include <iostream>
using namespace std;

class Test
{
public:
Test( int a)
{
x = a;
}
void print() const
{
cout << x << endl;
cout << this->x << endl;
cout << ( *this ).x << endl;
}
Test fun1()
{
x++;
return *this;
}
Test fun2()
{
x *= 10;
return *this;
}
private:
int x;
};

int main()
{
Test testObject( 12 );
testObject.fun1().fun2();
testObject.print();
return 0;
}
这段代码按照我的预期输出的X的值应该是130。可为什么会是13呢?

ls分析的很正确,我补充一下。

int main()
{
Test testObject(12 );
Test& ret1 = testObject.fun1(); //引用fun1返回的对象,是testObject执行完fun1的拷贝
//返回值相当于调用者中的局部变量
Test& ret2 = ret1.fun2(); //引用fun2返回的对象,是ret1执行完fun1的拷贝
testObject.print();
return 0;
}

因为你返回的是*this,并不是你main里建立的那个对象的指针,而是复制了一份。你这里有三个对象,一个x是13 两个x是130