【发布时间】:2018-11-02 11:37:43
【问题描述】:
我很困惑this 指针是什么意思,以及它是如何使用的。在下面的示例中给出相同的输出。在setX 和setY 函数中放置引用运算符(&)有什么区别?
#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)。 -
没有“引用运算符”之类的东西,在这种情况下,
&是Test &类型的一部分,因此函数返回对当前对象的引用,而不是复制的临时对象。 -
每个问题一个问题