重载==运算符C++

and*_*rew 2 c++ overloading operator-keyword

我做了+运算符的重载但现在我想重载= 2个长度的==运算符(可能是也可能不是相同的长度)并返回相应的结果.我该怎么做?我是否需要使用bool ==?

//我为重载+运算符做了什么来获得2个不同长度的新长度

Length operator+ (const Length& lengthA){       

    int newlengthMin = min, newlengthMax = max;

    if (lengthA.min < min)
        newLengthMin = lengthA.min;
    if  (lengthA.max > max)
        newLengthMax = lengthA.max;

    return Length(newLengthMin, newLengthMax);
}
Run Code Online (Sandbox Code Playgroud)

Gus*_*son 5

使用 bool 并确保添加const

bool operator==(const Length& lengthA) const { return ...; }
Run Code Online (Sandbox Code Playgroud)

您还可以使用两个参数(每个对象一个)将其设为全局。


Ale*_*ler 5

对于简单的情况,请使用bool operator==(const Length& other) const.注意const- 比较运算符不需要修改其操作数.你也不应该operator+!

如果要利用双方的隐式转换,请在全局范围内声明比较运算符:

bool operator==(const Length& a, const Length& b) {...}