修复重载运算符“ +”的使用不明确吗? [英] Fix use of overloaded operator '+' is ambiguous?
问题描述
我使用C ++ 11标准编写了以下代码:
I wrote the following code using C++11 standard:
.h文件:
#include "Auxiliaries.h"
class IntMatrix {
private:
Dimensions dimensions;
int *data;
public:
int size() const;
IntMatrix& operator+=(int num);
};
位我得到了并且错误地说:
Bit I am getting and error saying that:
错误:使用重载运算符'+'是模棱两可的(操作数类型为
'const mtm :: IntMatrix'和'int ')
return matrix + scalar;
error: use of overloaded operator '+' is ambiguous (with operand types 'const mtm::IntMatrix' and 'int') return matrix+scalar;
任何原因会导致这种现象,如何解决?
Any idea of what causes this behaviour and how may I fix it?
推荐答案
您在 mtm
命名空间中声明了运算符,因此定义应位于 mtm
命名空间。
You declared the operators in the mtm
namespace so the definitions should be in the mtm
namespace.
由于在外部定义了它们,所以实际上有两个不同的功能:
Since you define them outside, you've actually two different functions:
namespace mtm {
IntMatrix operator+(IntMatrix const&, int);
}
IntMatrix operator+(IntMatrix const&, int);
当您在矩阵+标量
中执行 operator +(int,IntMatrix const&)
,找到两个函数:
When you do matrix + scalar
in operator+(int, IntMatrix const&)
, both functions are found:
- 通过依赖于参数的查询 。
- 由于您位于全局名称空间中,因此位于全局名称空间中。
您需要定义操作符
在您声明它们的命名空间中, mtm
:
You need to define the operator
s in the namespace you declared them, mtm
:
// In your .cpp
namespace mtm {
IntMatrix operator+(IntMatrix const& matrix, int scalar) {
// ...
}
}
这篇关于修复重载运算符“ +”的使用不明确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!