我有一個矩陣類。我超載乘法運算符,但它的工作只有當我打電話矩陣標量;不適用於標量矩陣。我怎樣才能解決這個問題?如何重載乘法運算符?
#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;
}
編輯
我實現什麼chillsuggested,但我發現了以下錯誤:
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
我認爲你需要做的另一重載:檢查這http://stackoverflow.com/questions/10354886/simple-c-how-to-overload-the-multiplication-operator-so-that-floatmyclass -an – Pavenhimself
順便說一下,這個'Matrix tmp(rows,cols);'應該是這個'Matrix tmp(rows,cols);'。 –
chill