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

标签 c++ class operator-overloading

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

相关文章:

c++ - 如何将文件的特定部分读入私有(private)数据成员

c++ - 如何生成给定长度的字典字符串?

python - 将 CMakeLists.txt、boost-python 与 python setuptools 相结合

c++ - 在运行时生成机器指令的世界代码?

c++ - 类局部变量的指针?

java - 检查Java中的某些现有对象

c++运算符重载看不到其他运算符

C++,打印输出 (<<) 运算符重载

c++ - 如何将栈的pop实现为数组程序?

java - 如何在 Java 中实现成员明智比较?