2015-01-13 25 views
1

我试图在我的Matrix类中为*运算符重载。将类实例重载为右边的操作符

我有一个,使其如果是矩阵*的东西,(INT,双...)

我在寻找一个使之成为对面即东西*矩阵

这就是我想

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<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; 
}  

回答

2

ÿ OU应该让一个非成员,就是你写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; 

它不能编译,因为3Rational

你可以做的是使用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 
} 
+0

我试过这个,我得到了一些编译错误 main.cpp:71:5:错误:'operator *'不匹配(操作数类型是'int'和'Matrix ') m = 3 * m; ^ main.cpp中:71:5:注:候选是:3:: 在文件从main.cpp中包括0: Matrix.hpp:229:12:注意:模板矩阵&运算符*(常量T& ,常量矩阵&) 矩阵&运算符*(常量T&NUM,常量矩阵&MATR){ ^ Matrix.hpp:229:12:注意:模板参数推导/置换失败: main.cpp中:71: 6:注意:参数'T'('int'和'Rational')的推导冲突类型 m = 3 * m; ^ – keiloda

+0

@keiloda它有点不言自明 - “3”是“int”而不是“Rational”,因此类型不匹配。 –

+0

@keiloda请参阅我的更新以了解解决方法 –