【发布时间】:2018-11-21 05:25:45
【问题描述】:
我正在尝试将 >= 运算符重载到 Point 类,以便我可以比较指向 Point 实例的两个指针。但它看起来根本没有调用重载运算符,因为它没有打印调试输出。
为什么不调用重载运算符?如何让它发挥作用?
我正在尝试的代码在文件operator.cc:
#include <ios>
#include <iostream>
class Point {
int x, y;
public:
Point(int x, int y);
int getX();
int getY();
bool operator>=(Point* p);
};
Point::Point(int x, int y) {
this->x = x; this->y = y;
}
int Point::getX() {
return this->x;
}
int Point::getY() {
return this->y;
}
bool Point::operator>=(Point* p) {
std::cout << "overloaded>=" << std::endl; // does not print anything
return this->x >= p->getX() && this->y >= p->getY();
}
int main() {
Point* p1 = new Point(5, 5);
Point* p2 = new Point(4, 4);
bool result = p1 >= p2;
std::cout << std::boolalpha << result << std::endl;
return 0;
}
但是当我使用g++ operator.cc -o op && ./op 编译和运行这段代码时,我总是得到输出false,它不会打印overloaded>= 调试消息。
【问题讨论】:
-
你的重载在
Point和Point*之间,不是两个指针,后者不能重载。为什么不(*p1) >= (*p2)?另外,你为什么在这种情况下使用new? -
您在比较指针时会变得错误。将比较改为 *p1 >= *p2,将函数改为 bool Point::operator>=(const Point& p) 和函数体。
-
你的操作符会被
(*p1) >= p2调用 -
建议 -- 重载
<和==而不是>=。所有其他运算符都可以从这两个运算符中创建,而且您的类会立即变得更加健壮。 -
@SidS:如果您使用
std::find(例如)使用==(因为它可以用于定义相等但不排序的项目)。您可以从<合成==,但它不会自行发生。
标签: c++ pointers operator-overloading