I have a class 'number' with one member 'm_value' of type int64_t. I already overloaded = operator, there is code:
number& operator =(const number& right);
and it works fine with different types (e.g. int, int64_t, short, etc). In same way I overloaded operator:
number operator (const number& right);
But when I try to add class object with int64_t variable, it gives following error:
use of overloaded operator ' ' is ambiguous (with operand types 'number' and 'int64_t' (aka 'long'))
Of course, I can overload the operator for other types, but I'm wondering if there is another solution for this problem and why, in the case of the first operator, the conversion from one type to another occurs automatically?
Thanks in advice!
UPD: Here is 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);
};
CodePudding user response:
You have implicit conversions between your type and int64_t
that go both ways. This is asking for trouble, possibly in more ways than what you have just discovered.
Assuming
number x;
int64_t y;
the expression x y
can be resolved two ways, as x (number)y
and as (int64_t)x y
. Neither one is better than the other, hence the ambiguity.
There are several ways to resolve this.
- Make one of the conversions
explicit
. - Make both conversions
explicit
and do not use expressions likex y
. - Make both conversions
explicit
and define (lots and lots of) overloads that takenumber
andint64_t
operands.