c++ - 使用 "this"的成员函数的返回值

标签 c++ object

这个问题在这里已经有了答案:





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 前面在 setXsetY职能。我知道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/

相关文章:

c++ - 使用 valgrind 在内存泄漏检测中抑制 "dl-hack3-cond-1"

C++:在外部类中构造和销毁静态内部类实例

javascript - 如何从 Express Node.js 中的对象请求数据转换为字符串

javascript - 如何用javascript删除整个对象?

java - 如何使用 boolean equals(object o) 方法并调用该方法所应用的对象?

php - 如何使用减号访问对象属性?

c++ - 在方法定义中使用 inline 关键字是否可能会导致问题?

c++ - 未创建 NT 内核记录器 session 日志

c++ - 基于插入顺序的第一个最重复的单词

javascript - 如何将字符串转换为 map ?