我使用 C++11 标准编写了以下代码:
.h 文件:
#include "Auxiliaries.h"
class IntMatrix {
private:
Dimensions dimensions;
int *data;
public:
int size() const;
IntMatrix& operator+=(int num);
};
我得到的位和错误说:
错误:重载运算符"+"的使用不明确(使用操作数类型 'const mtm::IntMatrix' 和 'int'( 返回矩阵+标量;
知道是什么原因导致这种行为以及如何解决它吗?
您在mtm
命名空间中声明了运算符,因此定义应位于mtm
命名空间中。
由于您在外部定义它们,因此实际上有两个不同的函数:
namespace mtm {
IntMatrix operator+(IntMatrix const&, int);
}
IntMatrix operator+(IntMatrix const&, int);
当您在operator+(int, IntMatrix const&)
中执行matrix + scalar
时,可以找到这两个函数:
- 命名空间中通过参数相关查找的那个。 全局命名空间
- 中的那个,因为您在全局命名空间中。
您需要在声明它们的命名空间中定义operator
s,mtm
:
// In your .cpp
namespace mtm {
IntMatrix operator+(IntMatrix const& matrix, int scalar) {
// ...
}
}