vendredi 25 mars 2022

arithmetic operator overload c++ for different types

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);
};

Aucun commentaire:

Enregistrer un commentaire