【问题标题】:Overloading of operators with class instance as right-hand side以类实例作为右侧的运算符重载
【发布时间】:2015-01-13 11:38:52
【问题描述】:

我正在尝试对我的 Matrix 类中的 * 运算符进行重载。

如果它是 Matrix*something, (int, double...),我有一个可以做到的

我正在寻找一个适合另一面的东西,即某物*矩阵

这是我尝试过的

template<class T>
bool operator*(Matrix<T>& other ){
Matrix<T> mat(other.rows,other.columns);
for(int i=0;i<other.rows;i++){
    for(int j=0;j<other.columns;j++){
        T temp=other.get(i,j);
        temp=temp*(this);
        mat.set(i,j,temp);
    }
}
return mat;
}    

这就是 Matrix*something 的作用

 Matrix<T>& operator*(const T & num){
    Matrix<T> mat(rows,columns);
    for(int i=0;i<rows;i++){
        for(int j=0;j<columns;j++){
            T temp=(matrix[i][j]);
            temp=temp*num;
            mat.set(i,j,temp);
        }
    }
    return mat;
}    

【问题讨论】:

    标签: c++ templates matrix overloading operator-keyword


    【解决方案1】:

    你应该让它成为非成员,也就是说你在Matrix类之外写:

    template<class T>
    Matrix<T> operator*(const T& num, const Matrix<T>& mat) {
        return mat * num; // invoke existing implementation of Matrix * something
    }
    

    注意operator* 应该按值返回结果。您的实现中有一个错误,您返回对局部变量 mat 的悬空引用。

    请注意,此表单要求 numT 类型,因此如果像您的示例一样,您有

    Matrix<Rational> mat;
    mat = 3 * mat;
    

    它不会编译,因为3 不是Rational

    您可以做的是使用identity tricknum参数放在非推导上下文中,因此它将从int转换为Rational

    template<class T>
    Matrix<T> operator*(typename boost::mpl::identity<T>::type const& num, const Matrix<T>& mat) {
        return mat * num; // invoke existing implementation of Matrix * something
    }
    

    identity 在哪里

    template<typename T> 
    struct identity { typedef T type; };
    

    或者你可以这样做

    template<class T, class U>
    Matrix<T> operator*(const U& num, const Matrix<T>& mat) {
        return mat * num; // invoke existing implementation of Matrix * something
    }
    

    【讨论】:

    • 我试过这个,我得到了一些编译错误 main.cpp:71:5: error: no match for 'operator*' (operand types are 'int' and 'Matrix') m =3*米; ^ main.cpp:71:5: 注意:候选是:在 main.cpp:3:0 中包含的文件中:Matrix.hpp:229:12: 注意:模板 Matrix& operator*(const T&, const Matrix&) Matrix& operator*(const T& num,const Matrix &matr){ ^ Matrix.hpp:229:12: 注意:模板参数推导/替换失败:main.cpp :71:6: 注意:推导出参数 'T' 的冲突类型('int' 和 'Rational')m=3*m; ^
    • @keiloda 这有点不言自明 - 3int 而不是 Rational 所以类型不匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多