我有一个矩阵类。我正在重载乘法运算符,但只有当我调用 Matrix scalar 时它才有效;不适用于标量矩阵。我怎样才能解决这个问题?
#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;
}
已编辑
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