重载运算符不适用于为其定义的类

Overloaded operator isn't usable with the class it was defined for

本文关键字:定义 运算符 不适用 适用于 重载      更新时间:2023-10-16

我已经重载了运算符"-"来获取一个类的两个对象并输出一个新对象,但是当我使用它时,例如。 obj3 = obj1 - obj2,我收到一个错误,说没有运算符匹配这些操作数。

vctmath.h 中命名空间的声明:

#ifndef VCTMATH
#define VCTMATH
namespace vctmath {
Vect operator -(Vect a, Vect b);
}
#endif

主 vctmath 文件中的定义;

#include "Vect.h"
#include "vctmath.h"
Vect vctmath::operator -(Vect a, Vect b) {
Vect output(0);
output.SetX(a.GetX() - b.GetX());
return output;
}

这是 Vect.h 文件中的类声明

#ifndef VECT
#define VECT
class Vect {
private:
float x;
public:
Vect(float);
const float GetX(void);
void SetX(float a);
};
#endif

这就是Vect在Vect.cpp中的定义:

#include "Vect.h"
#include "vctmath.h"
Vect::Vect(float a): x(a) {}
const float Vect::GetX(void) { return x; };
void Vect::SetX(float a) {
x = a;
}

main 函数创建 Vect 类的两个对象,然后尝试使用新重载的 - 运算符:

#include "Vect.h"
#include "vctmath.h"
int main() {
Vect vect1(0);
Vect vect2(1);
Vect vect3 = vect1 - vect2; //this is where the problem is
return 0;
}

错误为 E0349;没有运算符 "-" 匹配这些操作数, 操作数类型为 Vect - Vect。

依赖于参数的查找不会在随机命名空间中搜索全局命名空间中类型的运算符重载。

Vectvctmath命名空间之间没有关系,因此编译器无法找到要使用的重载。

您可以:

  • 在使用运算符之前打开命名空间:using namespace vctmath
  • Vect移动到命名空间
  • 将运算符定义为成员方法,Vect::operator-

目前尚不清楚您如何定义 Vect。显然,在您显示的代码中,现在的问题在于命名空间内名称的可见性。建议在使用命名空间中定义的类时显式使用命名空间名称。

我建议您更改 Vector.h(并相应地.cpp(:

... 
namespace vctmath {
class Vect {
...
};       
} // namespace vctmath
....

主.cpp

int main() {
vctmath::Vect vect1(0);
vctmath::Vect vect2(1);
Vect vect3 = vect1 - vect2;
return 0;
}

如果由于某种原因您不想将 Vect 放入命名空间,您还有其他选择: a( 明确呼叫接线员:

Vect vect3 = vctmath::operator-(vect1, vect2);

b( 使用适配器设计模式:

Vect operator -(Vect& a, Vect& b) {
return vctmath::operator-(a, b);
}
int main() {
Vect vect1(0);
Vect vect2(1);
Vect vect3 = vect1 - vect2;
return 0;
}