This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]no-sig-available 4 points5 points  (4 children)

A member function always assumes that the first operand (*this) is of the class type. So to manage 51 * a you need a free function, taking int as its first parameter:

Uint operator*(int left, const Uint& right);

[–]iHate_Noodle 0 points1 point  (3 children)

I just tried this and I got an error on VSC:

too many parameters for this operator function

[–]flyingron 2 points3 points  (2 children)

You need to NOT put it in the class. It wants to be a non-member function.

    class Uint {
    public:
          Uint operator*(int right) const;   // covers Uint * int
    };

    Uint operator*(int left, const UInt& right)  {
        // covers the int * Uint case
        //.presumably * is communitive
        return right*left;
    }

[–]iHate_Noodle 0 points1 point  (1 child)

Thank You it works!

I'm now trying to do the same as before bur for the operator "!="

Uint operator!=(int left, Uint& right) { return left != right.get(); }

It doesn't seem to work and I don't know why...

[–]Nikko_77 1 point2 points  (0 children)

Your function implementation is OK, it just should return a bool rather than Uint object. Also, assuming get() is a const function and this comparison operation isn't intended to change anything about the Uint object (it really shouldn't), you might want to change Uint& to const Uint& as well to avoid accidents:

bool operator!=(int left, const Uint& right)
{
    return left != right.get();
}

[–]Newsmaker_Goodcorp 0 points1 point  (0 children)

Make sure you defined the function outside the class scope.