2

I'm currently coding a class to make a bunch of matrices operations, and one of them is to multiply a matrix with a number. I successfully made Matrix * 2 p.e. but I want to do 2 * Matrix. Is that possible? And how?

This is the signature of the first operator overloading (Matrix * double) : Matrix Matrix::operator* (const double& b)

Anunciada
  • 31
  • 2
  • 2
    I recommend that you read [this canonical implementations reference](https://en.cppreference.com/w/cpp/language/operators#Canonical_implementations). Especially the part about [binary arithmetic operators](https://en.cppreference.com/w/cpp/language/operators#Binary_arithmetic_operators). – Some programmer dude Jun 17 '20 at 16:18

1 Answers1

1

So, you can overload operator* like this:

class t
{
private:
    int f;
public:
    t(const int& i) : f(i) {}
    friend t& operator*(const int& a, t&);
    int get() const
    {
        return f;
    }
};

t& operator*(const int& a, t& obj)
{
    obj.f *= a;
    return obj;
}

int main()
{
    t obj(5);
    obj = 2 * obj;
    std::cout << obj.get();
}

result: 10

NixoN
  • 557
  • 3
  • 16