我使用 C++11 标准编写了以下代码:
.h文件:
#include "Auxiliaries.h"
class IntMatrix {
private:
Dimensions dimensions;
int *data;
public:
int size() const;
IntMatrix& operator+=(int num);
};
我得到的位和错误的说法是:
error: use of overloaded operator '+' is ambiguous (with operand types 'const mtm::IntMatrix' and 'int') return matrix+scalar;
知道是什么原因导致了这种行为,我该如何解决?
最佳答案
您在 mtm
命名空间中声明了运算符,因此定义应该在 mtm
命名空间中。
由于您在外部定义它们,因此您实际上拥有两个不同的函数:
namespace mtm {
IntMatrix operator+(IntMatrix const&, int);
}
IntMatrix operator+(IntMatrix const&, int);
当您在 operator+(int, IntMatrix const&)
中执行 matrix + scalar
时,会找到两个函数:
- 命名空间中的一个通过Argument-Dependent Lookup .
- 全局命名空间中的一个,因为您位于全局命名空间中。
您需要在声明它们的命名空间中定义operator
,mtm
:
// In your .cpp
namespace mtm {
IntMatrix operator+(IntMatrix const& matrix, int scalar) {
// ...
}
}
关于c++ - 修复重载运算符 '+' 的使用不明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62347462/