我对 C++ 很陌生,而且我有指针问题。有人可以解释一下这个代码如何为 y 返回 0 而不是 20 吗?
#include <iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
Test setX(int a) { x = a; cout << "hello"; return *this; }
Test setY(int b) { y = b; cout << "world"; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1;
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
您的方法正在返回测试对象的副本。
Test setX(int a) { x = a; cout << "hello"; return *this; }
Test setY(int b) { y = b; cout << "world"; return *this; }
Run Code Online (Sandbox Code Playgroud)
所以obj1.setX(10)适用于原件,但.SetY(20)适用于副本。
您需要通过引用返回:
Test& setX(int a) { x = a; cout << "hello"; return *this; }
Test& setY(int b) { y = b; cout << "world"; return *this; }
Run Code Online (Sandbox Code Playgroud)