我有一個類“數字”,其中一個成員“m_value”型別為 int64_t。我已經多載了 = 運算子,有代碼:
number& operator =(const number& right);
它適用于不同的型別(例如 int、int64_t、short 等)。以同樣的方式,我多載了 運算子:
number operator (const number& right);
但是當我嘗試使用 int64_t 變數添加類物件時,會出現以下錯誤:
use of overloaded operator ' ' is ambiguous (with operand types 'number' and 'int64_t' (aka 'long'))
當然,我可以為其他型別多載運算子,但我想知道這個問題是否有另一種解決方案,為什么在第一個運算子的情況下,從一種型別到另一種型別的轉換會自動發生?
謝謝指教!
UPD:這是類標題:
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);
};
uj5u.com熱心網友回復:
您的型別之間有隱式轉換,并且int64_t是雙向的。這是自找麻煩,可能比你剛剛發現的更多。
假設
number x;
int64_t y;
該運算式x y可以通過兩種方式決議,asx (number)y和 as (int64_t)x y。沒有一個比另一個更好,因此模棱兩可。
有幾種方法可以解決這個問題。
- 進行轉換之一
explicit。 - 進行兩種轉換,不要
explicit使用像x y. - 進行轉換
explicit并定義(很多很多)采用number和int64_t運算元的多載。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450762.html
