我创建了一个类Matrix
,它基本上代表了一个数学矩阵。为了使用标量矩阵乘法,我将*
运算符重载为:
Matrix Matrix::operator*(double scalar) const
{
Matrix result(*this);
result *= scalar;
return result;
}
为了使操作员也从左开始工作,我使用了:
Matrix operator*(double a, const Matrix &M)
{
return M * a;
}
鉴于Matrix M
和double s
,M * s
工作正常但s * M
给了我一个错误:
错误C2677:二进制
*
:找不到类型为Matrix
的全局运算符(或者没有可接受的转换)
IDE显示错误:“没有运算符*
匹配这些操作数”。
知道可能是什么问题吗?
编辑:这是一个愚蠢的错误!我没有在标题中声明运算符,编译器无法看到声明!很抱歉...
答案 0 :(得分:8)
当我按照FAQ entry on operator overloading中给出的建议(特别是关于二进制算术运算符的段落)时,我无法重现您的错误。
这对我来说很好:
struct M {
M& operator*= (float f) {
// multiply this by f
return *this;
}
};
inline M operator* (M m, float f) {
m *= f;
return m;
}
inline M operator* (float f, M m) {
return m * f;
}
int main() {
M m;
float f;
m * f;
f * m;
}
我希望这会有所帮助。如果没有,请提供更多代码。