重载运算符不适用于为其定义的类
Overloaded operator isn't usable with the class it was defined for
我已经重载了运算符"-"来获取一个类的两个对象并输出一个新对象,但是当我使用它时,例如。 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。
依赖于参数的查找不会在随机命名空间中搜索全局命名空间中类型的运算符重载。
Vect
和vctmath
命名空间之间没有关系,因此编译器无法找到要使用的重载。
您可以:
- 在使用运算符之前打开命名空间:
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;
}
相关文章:
- 在 C++ 的自定义运算符中删除与删除[](不同于常见的删除与删除[]问题)
- 自定义运算符重载C++,无开销
- 如何为缺少预定义运算符而不扩展命名空间"std"的标准类型定义运算符>> (istream &, ...)?
- 如何使用C++将MXNET自定义运算符构建到单独的库/包中?
- 模板类的用户定义运算符上的 C++ 隐式转换
- 什么是编程语言支持定义您自己的自定义运算符?
- 如何在Qt中为矩阵类定义[ ][ ]运算符?
- 在 c++ 迭代器中,我应该同时定义运算符== 和运算符!=吗?
- 在 rxcpp 中创建自定义运算符
- 错误 C2676;在C++的二叉搜索树类中定义 ++ 运算符时遇到问题
- std::map :使用自定义运算符时更新密钥
- 最初定义运算符C++在哪里
- 如何在Tensorflow Lite中添加自定义运算符
- 如何在 rxcpp 自定义运算符中正确推断泛型
- 在模板化类之外定义运算符重载
- 为类定义之外的模板类定义运算符[]()(数组订阅)
- 是否可以在类定义之外定义运算符[]()(数组订阅)
- C++ 重新定义运算符<() 和运算符!=()
- 如何将上下文信息传递给自定义运算符<<适用于 std::iostream
- 无法在C++中定义++运算符,这里有什么问题?