【发布时间】:2019-09-09 22:49:26
【问题描述】:
我已经重载了运算符“-”来获取一个类的两个对象并输出一个新对象,但是当我使用它时,例如。 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;
}
主函数创建 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。
【问题讨论】:
-
@KaenbyouRin 哎呀:P
-
那仍然不是minimal reproducible example。但它更接近。至少我们现在可以看到问题所在。
-
@LightnessRacesinOrbit 现在似乎是命名空间的问题。我的直觉是正确的。 :P
-
@KaenbyouRin 是的,对不起,哈哈。我不知道你可以限定这样的函数定义。
标签: c++ class operator-overloading