这个问题在这里已经有了答案:
What are the differences between a pointer variable and a reference variable in C++?
(42 个回答)
2年前关闭。
在以下类定义中:
#include<iostream>
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; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
我不明白为什么我们应该放一个
*
在 this
前面在 setX
或 setY
职能。我知道this
是指向当前对象的指针,*
返回指向的对象,但由于存在 &
在函数的返回值中,这意味着函数返回对 Test
的引用目的。那么,返回变量不应该也是一个引用(即指针),如下所示:Test &setX(int a) { x = a; return this; }
?
作为替代,我相信
Test setX(int a) { x = a; return *this; }
也是正确的,因为返回值不是指针,而是指向的对象,类型为
Test
(而不是指向 Test
的类型指针:Test&
)。为什么,如果是这样,他们不正确吗?
最佳答案
Then,shouldn't the return variable also be a reference (that is a pointer), like this:
Test &setX(int a) { x = a; return this; }
那将是编译器错误。
this
是一个指针。无法转换为引用类型 Test&
.但是,当您取消引用 this
,可作为引用类型Test&
. This& temp = this; // An error.
This& temp = *this; // OK
将您的功能重新想象为:Test &setX(int a)
{
x = a;
// This& temp = this; // Error
This& temp = *this; // OK
return temp;
}
关于c++ - 使用 "this"的成员函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59254976/