繁体   English   中英

不同类型的算术运算符重载 c++

[英]arithmetic operator overload c++ for different types

我有一个 class 'number' 和一个类型为 int64_t 的成员 'm_value'。 我已经重载了 += 运算符,有代码:

number& operator+=(const number& right);

它适用于不同类型(例如 int、int64_t、short 等)。 以同样的方式我重载了 + 运算符:

number operator+(const number& right);

但是当我尝试用 int64_t 变量添加 class object 时,它会出现以下错误:

use of overloaded operator '+' is ambiguous (with operand types 'number' and 'int64_t' (aka 'long'))

当然,我可以为其他类型重载运算符,但我想知道是否有针对此问题的另一种解决方案,以及为什么在第一个运算符的情况下,会自动从一种类型转换为另一种类型?

谢谢指教!

UPD:这是 class header:

class number {
private:
    int64_t m_value;
public:
    number();
    number(int64_t value);
    number(const number& copy);
 
    number& operator=(const number& other);
 
    number& operator++();
    number operator++(int);
 
    number& operator--();
    number operator--(int);
 
    number& operator+=(const number& right);
    number& operator-=(const number& right);
    number& operator*=(const number& right);
    number& operator/=(const number& right);
    number& operator%=(const number& right);
 
    number& operator&=(const number& right);
    number& operator|=(const number& right);
    number& operator^=(const number& right);
 
    number operator+(const number& right);
    number operator-(const number& right);
    number operator*(const number& right);
    number operator/(const number& right);
    number operator%(const number& right);
    
    number operator&(const number& right);
    number operator|(const number& right);
    number operator^(const number& right);
 
    operator bool() const;
    operator int() const;
    operator int64_t() const;
    operator std::string() const;
 
    friend std::ostream& operator<<(std::ostream& out, const number& num);
    friend std::istream& operator>>(std::istream& in, number& num);
};

您的类型和go之间的int64_t之间存在隐式转换。 这是在自找麻烦,其方式可能比您刚刚发现的更多。

假设

number x;
int64_t y;

表达式x + y可以通过两种方式解析,如x + (number)y(int64_t)x + y 没有一个比另一个更好,因此模棱两可。

有几种方法可以解决这个问题。

  • 使其中一个转换explicit
  • 使这两种转换都explicit进行,并且不要使用x + y之类的表达式。
  • explicit转换并定义(很多很多)采用numberint64_t操作数的重载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM