C++ operator overloading to do double * object

Viewed 51

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)

1 Answers

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

Related