【问题标题】:How can I overload the multiplication operator?如何重载乘法运算符?
【发布时间】: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;
}

已编辑


我实现了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

【问题讨论】:

标签: c++ operator-overloading matrix-multiplication


【解决方案1】:

不要让运营商成为会员。定义一个operator*= 作为Matrix 的成员,然后定义两个免费的operator*,在它们的实现中使用*=

【讨论】:

    【解决方案2】:

    在类外定义一个operator*,它只是颠倒了参数。并将另一个operator* 声明为const

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

    【讨论】:

    • 我试过你的选择,但我得到他以下错误:main.cpp:44:19: 错误:'12 * u2' main.cpp:44 中的'operator*' 不匹配:19: 注意: 候选是: lcomatrix/lcomatrix.hpp:149:11: 注意: template Matrix operator*(T, const Matrix&)
    • 您的矩阵很可能没有使用int 类型实例化。
    【解决方案3】:

    类成员operator * 对其对应的对象(左侧)进行操作,调用M * scalar 对应于A.operator*(scalar) - 如果您切换顺序,这显然不适用,因为您没有定义 operator *为标量。您可以创建一个全局 operator * 实现,它接受标量作为第一个(左)操作数,接受矩阵作为第二个操作数。在实现内部切换顺序并调用您的 inclass 类operator *。例如:

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

    【讨论】:

    • 这是一个灾难的秘诀 - 你返回一个对象的引用,它很快就会消失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2021-07-18
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多