Kicsi Mano
Kicsi Mano

Reputation: 3761

How can I overload the multiplication operator?

I have a Matrix class. I am overloading the multiplication operator, but it's working only if I call Matrixscalar; isn't working for scalarMatrix. How can I fix this?

#include <iostream>
#include <stdint.h>

template<class T>
class Matrix {
public:
    Matrix(unsigned rows, unsigned cols);
    Matrix(const Matrix<T>& m);
    Matrix();
    ~Matrix(); // Destructor

Matrix<T> operator *(T k) const;

    unsigned rows, cols;
private:
    int index;
    T* data_;
};

template<class T>
Matrix<T> Matrix<T>::operator *(T k) const { 
    Matrix<double> tmp(rows, cols);
    for (unsigned i = 0; i < rows * cols; i++)
        tmp.data_[i] = data_[i] * k;

    return tmp;
}

template<class T>
Matrix<T> operator *(T k, const Matrix<T>& B) {
    return B * k;
}

Edited


I implemented what chill suggested, but I'm getting the following error:

main.cpp: In function ‘int main(int, char**)’:
main.cpp:44:19: error: no match for ‘operator*’ in ‘12 * u2’
main.cpp:44:19: note: candidate is:
lcomatrix/lcomatrix.hpp:149:11: note: template<class T> Matrix<T> operator*(T, const Matrix<T>&)
make: *** [main.o] Error 1

Upvotes: 0

Views: 8535

Answers (3)

SomeWittyUsername
SomeWittyUsername

Reputation: 18348

The class member operator * operates on it's corresponding object (to the left), invoking M * scalar corresponds to A.operator*(scalar) - this obviously doesn't apply if you switch the order since you don't have operator * defined for the scalar. You can create a global operator * implementation which accepts scalar as first (left) operand and matrix as the second. Inside the implementation switch the order and invoke your inclass class operator *. E.g.:

template <class T>
Matrix<T> operator *(T scalar, const Matrix<T> &M)
{
    return M * scalar;
}

Upvotes: 0

chill
chill

Reputation: 16888

Define an operator* outside the class, which just reverses the arguments. And declare the other operator* as const.

template<typename T> Matrix<T> operator* (T k, const Matrix<T> &m) { return m * k; }

Upvotes: 2

James Kanze
James Kanze

Reputation: 153909

Don't make the operator a member. Define an operator*= as a member of Matrix, then define two free operator*, using *= in their implementation.

Upvotes: 3

Related Questions