简体   繁体   English

如何重载乘法运算符?

[英]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 Matrix scalar; 我正在重载乘法运算符,但是仅当我调用Matrix 标量时 ,它才起作用 isn't working for scalar Matrix. 不适用于标量矩阵。 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: 我实现了chill的 建议 ,但出现以下错误:

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

Don't make the operator a member. 不要让操作员成为成员。 Define an operator*= as a member of Matrix, then define two free operator* , using *= in their implementation. 定义一个operator*=作为Matrix的成员,然后定义两个自由operator* ,在实现中使用*=

Define an operator* outside the class, which just reverses the arguments. 在类外定义一个operator* ,它只会反转参数。 And declare the other operator* as const . 并将另一个operator*声明为const

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

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. 类成员operator *在其对应的对象上操作(向左),调用M * scalar对应于A.operator*(scalar) -如果您未定义运算符*,则切换顺序显然不适用标量。 You can create a global operator * implementation which accepts scalar as first (left) operand and matrix as the second. 您可以创建一个全局operator *实现,该实现将标量作为第一个(左)操作数,将矩阵作为第二个。 Inside the implementation switch the order and invoke your inclass class operator * . 在实现内部,切换顺序并调用inclass类operator * Eg: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM