【问题标题】:Usage of this pointer in c++ [duplicate]在c ++中使用此指针[重复]
【发布时间】:2018-11-02 11:37:43
【问题描述】:

我很困惑this 指针是什么意思,以及它是如何使用的。在下面的示例中给出相同的输出。在setXsetY 函数中放置引用运算符(&)有什么区别?

#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; return *this; }
  Test setY(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
  Test obj1;
  obj1.setX(10).setY(20);
  obj1.print();
  return 0;
}

带引用运算符

#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; return *this; }
  Test &setY(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
  Test obj1;
  obj1.setX(10).setY(20);
  obj1.print();
  return 0;
}

【问题讨论】:

  • 当您按值返回Test 时,您将返回对象的副本。如果您通过引用返回 Test,您将收到对您当前正在处理的确切对象的引用(即 *this)。
  • 没有“引用运算符”之类的东西,在这种情况下,&amp;Test &amp; 类型的一部分,因此函数返回对当前对象的引用,而不是复制的临时对象。
  • 每个问题一个问题

标签: c++ this


【解决方案1】:

当你按值返回时,如

Test setX(int a) { x = a; return *this; }

然后您返回对象的副本。并且副本与原始对象完全无关。

当你返回一个引用时,你返回的是一个对实际对象的引用,不会复制。

由于这种差异,您展示的两个程序应该产生相同的输出。第一个应该说x 等于10(因为你在obj1 对象上设置了x)但是你在setX 返回的副本上设置了y,这意味着obj1.y 将仍然为零。 See e.g. this example.

【讨论】:

    猜你喜欢
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2018-11-03
    • 1970-01-01
    • 2020-03-21
    • 2019-04-13
    相关资源
    最近更新 更多