我正在为教育目的制作一个包含模板的自定义矩阵类。我希望我的 类以下列方式工作:二进制'运算符*'的参数太多
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)
请添加更多上下文。我怀疑是你在类的定义中放置了'matrix operator *(T&a,matrix & mat);' –
2014-10-30 16:18:34
尝试在第二个函数的参数中加入'const'?可能无法将非const引用传递给文字'2'。 – 2014-10-30 16:19:05
我做了这两个,它的工作。你能解释这是为什么吗?我想在这里学习更多的C++。 – msmechanized 2014-10-30 16:21:47