与this
指针有关,我希望有人认为以下两个代码段是否实现相同的功能。
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
传递对&
对象的引用相同的功能。
答案 0 :(得分:2)
在选择所需选项之前,请注意@RemyLebeau提到的这篇文章:What are the basic rules and idioms for operator overloading?
两者之间差异的示例:
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;
}