此指针 - 按值返回 vs 按引用返回

  • 本文关键字:返回 vs 引用 指针 c++
  • 更新时间 :
  • 英文 :


关于this指针,我想听听某人的意见,以下 2 段代码是否实现了相同的功能。

Position Position::operator = (Position pos)
{
this->x = pos.x;
this->y = pos.y;
return *this;
}

Position & Position::operator = (Position pos)
{
this->x = pos.x;
this->y = pos.y;
}

我知道第一个片段更常用。但是,我想确认第二个代码段是否具有与我使用&传递对this对象的引用相同的功能。

在选择所需的选项之前,请注意@RemyLebeau提到的这篇文章: 运算符重载的基本规则和习语是什么?

两者之间的差异示例:

class Position1 {
public:
int x, y;
Position1 operator=(Position1 pos)
{
this->x = pos.x;
this->y = pos.y;
return *this;
}
};
class Position2 {
public:
int x, y;
Position2& operator=(Position2 pos)
{
this->x = pos.x;
this->y = pos.y;
return *this;
}
};
int main() {
Position1 p11, p12;
Position2 p21, p22;
//Position1 *p13 = &(p12 = p11); // Compilation error: Taking address of temporary object..
p21.y = 20;
p21.x = 10;
Position2 *p23 = &(p22 = p21); // Working - the `temporary object` is a reference to non temporary object.
p23->x = 99;
p23->y = 84;
cout << p21.x << " " << p21.y; // didn't change
cout << p22.x << " " << p22.y; // changed
cout << p23->x << " " << p23->y; // changed
//===================================================
//(p12 = p11).y = 3; // Compiling error: Expression is not assignable
(p22 = p21).y = 3; // works
cout << p21.x << " " << p21.y << endl; // didn't change
cout << p22.x << " " << p22.y << endl; // changed
return 0;
}

最新更新