overload greater than operator with or without fri

2019-09-18 20:37发布

问题:

Suppose I have the following class:

class Point{
private:
int x,y;

public:
int get_x() const {return x;}
int get_y() const {return y;}

Point() :x(0),y(0){}
Point(int x,int y):x(x),y(y){}
Point(const Point& P){
    x = P.get_x();
    y = P.get_y();
}
Point& operator=   (const Point& P) {
            x = P.get_x();
            y = P.get_y();

    return *this;
}
friend ostream& operator<<(ostream& os,const Point& P) {

    os<<"["<<P.get_x()<<", "<<P.get_y()<<"]";
    return os;
}


Point operator - (const Point &P){
    return Point(x-P.get_x(),y-P.get_y());
}

friend bool operator > (const Point &A, const Point &B) {
    return A.get_y()>B.get_y();
}


};

Here I used friend function. I can also use function without friend:

class Point{
...
bool operator > (const Point &B) const {
    return y>B.get_y();
}
 ...

};

What are the differences between them in actual implementations? Also in the second method, the code won't compile without 'cont', why is that? Even after I changed the getter function into non-const function, it still won't compile without the 'const'.

回答1:

As you've already noticed, comparison operator overloads can either be implemented as a member function or as a non-member function.

As a rule of thumb you should implement them as a non-member non-friend function where possible, as this increases encapsulation, and it allows (non-explicit) conversion constructors to be used on either side of the operator.

Say for instance your Point class for whatever reason had an int conversion constructor:

Point(int x);

With a non-member comparison operator you can now do the following:

Point p;
p < 3; // this will work with both a member and non-member comparison
3 < p; // this will **only** work if the comparison is a non-member function

You also seem to be confused about when to use const, again as a rule of thumb for comparison operators you should always use const wherever possible, because comparisons logically do not involve any change to the object.

As Point is a very small class you could also take it by value instead, so in order of most to least preferable your options are:

// Non-member, non-friend
bool operator>(Point const& A, Point const& B);
bool operator>(Point A, Point B);

// Non-member, friend    
friend bool operator>(Point const& A, Point const& B);
friend bool operator>(Point A, Point B);

// Member
bool Point::operator>(Point const& B) const;
bool Point::operator>(Point B) const;