2014-10-30 24 views
2

我正在为教育目的制作一个包含模板的自定义矩阵类。我希望我的 类以下列方式工作:二进制'运算符*'的参数太多

mat*2; //Works 
2*mat; //Should also work 

因为我有以下声明

matrix<T> operator*(const T& a) const; 

和implemenetation

template <typename T> 
matrix<T> matrix<T>::operator*(const T& a) const{ 
//Implementation here 
} 

第一种情况。而第二种情况下,我必须作为非会员类别实施

matrix<T> operator*(T& a, matrix<T>& mat); 

与实施

template<typename T> 
matrix<T> operator*(T& a, const matrix<T>& mat){ 
    return mat*a; 
} 

但是当我尝试编译此我得到使用MSVC

error C2804: binary 'operator *' has too many parameters 
..\main.cpp(33): error C2678: binary '*' : no operator found which takes a left hand operand of  type 'int' (or there is no acceptable conversion) 
+1

请添加更多上下文。我怀疑是你在类的定义中放置了'matrix operator *(T&a,matrix & mat);' – 2014-10-30 16:18:34

+1

尝试在第二个函数的参数中加入'const'?可能无法将非const引用传递给文字'2'。 – 2014-10-30 16:19:05

+0

我做了这两个,它的工作。你能解释这是为什么吗?我想在这里学习更多的C++。 – msmechanized 2014-10-30 16:21:47

回答

4

的第一个参数类型下面的错误必须要么TT const &

甲非const 左值引用不能结合于字面像2(或到一个临时或const对象或参考)。

2

根据我的评论:非静态类方法具有类类型的隐式第一个参数(*this)。您定义的运算符是否放在类定义中将有三个参数(而二进制operator*应该只有2个)。如果将运算符声明放在类定义中,则需要删除第一个参数并直接使用类字段。