gpt4 book ai didi

c++ - 重载运算符不能用于为其定义的类

转载 作者:行者123 更新时间:2023-11-28 04:10:41 28 4
gpt4 key购买 nike

我已经重载了运算符“-”以获取一个类的两个对象并输出一个新对象,但是当我使用它时,例如。 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.cpp 中 Vect 的定义:

#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。

最佳答案

Argument-dependent lookup不会在随机命名空间中搜索全局命名空间中类型的运算符重载。

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

您可以:

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

关于c++ - 重载运算符不能用于为其定义的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57862053/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com