C++ 赋值运算符重载意外行为

问题描述 投票:0回答:1

我是 C++ 新手,正在尝试以正确的方式学习它。特别是,我正在下面的课程中练习一个简单的赋值运算符重载

class Point {
public:
    int x;
    int y;
    Point():x(0),y(0){};
    Point operator=(Point Y);
};

赋值运算符是:

Point Point::operator=(Point Y){
    Point temp;
    temp.x = Y.y;
    temp.y = Y.x;
std::printf("temp has coordinates %d, %d\n",temp.x,temp.y);
return temp;
}

当我在 main 中有以下内容时,我不明白为什么我最终没有得到 B.x = 0, B.y = 3。

int main()
{
    Point A;
    Point B;
    A.x = 3;
    B = A;
    std::printf("B has coordinates %d, %d\n",B.x,B.y);
    return 0;
}

我知道在我的例子中我没有使用指向 B 的隐式 this 指针,并且代码进行了多余的复制,并且有一种更好的方法可以通过引用作为参数类型来实现这一点。但是 temp 有以下字段:temp.x = 0,temp.y = 3,那么为什么 B 最终没有得到它们呢?

c++ operator-overloading variable-assignment
1个回答
1
投票

您的赋值运算符不会更改调用它的对象。它创建一个临时对象,该对象是由赋值运算符分配和返回的,并且不在程序中使用。

赋值运算符应如下所示

class Point {
public:
    int x;
    int y;
    Point():x(0),y(0){};
    Point &operator=( const Point &);
};

Point & Point::operator=( const Point &Y )
{
    x = Y.y;
    y = Y.x;
    //std::printf("temp has coordinates %d, %d\n",temp.x,temp.y);
    return *this;
}
© www.soinside.com 2019 - 2024. All rights reserved.