修复重载运算符“+”的使用不明确?
Fix use of overloaded operator '+' is ambiguous?
我使用 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++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) {
// ...
}
}