【发布时间】:2014-10-30 16:16:26
【问题描述】:
我正在制作一个带有模板的自定义矩阵类,用于教育目的。我要我的课 按以下方式工作:
mat*2; //Works
2*mat; //Should also work
对于第一种情况,我有以下声明
matrix<T> operator*(const T& a) const;
和实现
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<T> operator*(T& a, matrix<T>& mat);。 -
试试在第二个函数的参数中加入
const?它可能无法传递对文字2的非常量引用。 -
这两件事我都做了,而且效果很好。你们能解释一下为什么会这样吗?我正在尝试在这里学习更多 C++。 :)
标签: c++ templates operator-overloading