You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++赋值运算符重载出现意外行为的原因咨询

为什么重载赋值运算符后B的坐标不是(0,3)?

你定义的Point类代码:

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函数代码:

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;
}

你的疑问:明明temp的坐标是(0,3),为什么B最终没有获得这些值?


核心问题是你的赋值运算符根本没修改调用它的对象(也就是B),只是创建了一个局部临时对象temp并返回,完全没碰B本身的成员变量。

当执行B = A时,实际调用的是B.operator=(A),此时this指针指向的就是B,但你的实现里完全忽略了this,只是操作了临时的temp对象。temp的坐标确实是(0,3),但这个对象和B没有任何关系——你既没把temp的值赋给B,也没直接修改B的x和y,所以B还是保持默认构造函数初始化的(0,0)。

正确的赋值运算符实现

首先修改类内的函数声明,把参数改成const引用(避免不必要的拷贝),返回值改成当前对象的引用(符合C++赋值运算符的惯例,支持链式赋值):

class Point {
public:
    int x;
    int y;
    Point():x(0),y(0){};
    Point& operator=(const Point& Y); // 修改声明
};

然后实现时,直接通过this指针修改当前对象的成员:

Point& Point::operator=(const Point& Y){
    // 直接修改调用该运算符的对象(也就是B)的成员
    this->x = Y.y;
    this->y = Y.x;
    std::printf("当前对象坐标:%d, %d\n", this->x, this->y);
    return *this; // 返回当前对象的引用,支持链式赋值(比如 B = A = C)
}

这样执行B = A时,B的x和y会被直接修改为Y.y(也就是A.y=0)和Y.x(也就是A.x=3),最终B的坐标就是(0,3),符合你的预期。


内容的提问来源于stack exchange,提问作者Artin Ostal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 23:42:22