简体   繁体   中英

overloading >= operator to compare pointers

I am trying to overload >= operator to Point class, so that I could compare two pointers to Point instances. But it does not look it calls the overloaded operator at all, because it is not printing the debug output. Why the overloaded operator is not called? How to make it work?

The code I am trying is in file 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;
}

But when I compile and run this code with g++ operator.cc -o op && ./op , then I always get output false , and it doesn't print the overloaded>= debug message.

You almost always want to compare actual Point objects, not a pointer to a Point .

bool Point::operator>=(Point const & p) {
    std::cout << "overloaded>=\n"; // should now print something
    return x >= p.x && y >= p.y;
}

Then you'd invoke it like:

int main() {
    Point p1{5, 5};
    Point p2{4, 4};
    std::cout << std::boolalpha << (p1>=p2) << '\n';
}

As a side note, if you support comparison in C++, it's (much) more common to overload operator< instead. By default standard algorithms will compare for less than, rather than greater than/equal to.

But, if you do decide to implement operator< for use with standard algorithms, you'll have to ensure that it carries out a "strict weak" comparison, which your current comparison is not (as it stands now, there are values of A and B (eg, {4,5} and {5,4}) for with both A>=B and B>=A will return false, indicating that A is neither less than, nor equal to, nor greater than B. A comparison operator like that can (and often will) produce undefined behavior from things like sorting algorithms.

To invoke a member function of a class from a pointer to an object, the following approach is used. Suppose there is another function in class Point named cmp which takes a pointer as an argument.

bool Point::cmp(Point *p)
{
return true;
}

It can be invoked by pointer p1 by (*p1).cmp(p2) .

Similarly, the overloaded operator >= can also be invoked via:

bool result = *p1 >= p2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM