【发布时间】:2012-11-22 13:59:43
【问题描述】:
我有一个矩阵类。我正在重载乘法运算符,但只有当我调用 Matrixscalar; 时它才有效。不适用于标量矩阵。我该如何解决这个问题?
#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
【问题讨论】:
-
我认为您需要再次重载:检查此stackoverflow.com/questions/10354886/…
-
顺便说一下,这个
Matrix<double> tmp(rows, cols);应该是这个Matrix<T> tmp(rows, cols);。
标签: c++ operator-overloading matrix-multiplication