重载=带有浮点参数的c++中的运算符

Overloading = operator in c++ with float argument

本文关键字:c++ 运算符 参数 重载      更新时间:2023-10-16

我有以下程序:

#include <iostream>
using namespace std;
class N {
public:
    float x;
    N(){ x = 3.0; }
    N(float y){ x = y; }
    N &operator=(float f){ return *new N(f); }
};

int main(){
    N a;
    a = 2.0;
    cout << a.x;
    return 0;
}

我希望结果是2(因为运算符=的定义),但它给了我3(就像没有a=2.0行一样)。有人能解释一下为什么会发生这种情况吗?"运算符="的定义有什么问题吗?非常感谢。

您的复制赋值操作符应该设置x的值,然后返回对*this的引用,如下所示:

N &operator =(float f) { x = f; return *this; }

相反,复制赋值操作符在堆上构造一个新的N实例,并返回对它的引用。

您不应该使用new,C++不是java。

N& operator=(float f)
{ 
    x = f; 
    return *this; 
}

试试这个。