Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading less than operator

I am overloading a less than operator for a class like so:

#include<string>
using namespace std;

class X{
public:
    X(long a, string b, int c);
    friend bool operator< (X& a, X& b);

private:
    long a;
    string b;
    int c;
};

and then the implementation file:

#include "X.h"


bool operator < (X const& lhs, X const& rhs)
{
    return lhs.a< rhs.a;
}

However it is not letting me access the a data member in the implementation file because a is declared as a private data member, even though its through an X object?

like image 303
user997112 Avatar asked Sep 05 '13 21:09

user997112


2 Answers

The friend function does not have the same signature as the function defined function:

friend bool operator< (X& a, X& b);

and

bool operator < (X const& lhs, X const& rhs)
//                 ^^^^^         ^^^^^

You should just change the line in your header file to:

friend bool operator< ( X const& a, X const& b);
//                        ^^^^^       ^^^^^

As you don't modify the objects inside the comparison operators, they should take const-references.

like image 176
Pierre Fourgeaud Avatar answered Oct 08 '22 16:10

Pierre Fourgeaud


You have declared a different friend function to the one you are trying to use. You need

friend bool operator< (const X& a, const X& b);
//                     ^^^^^       ^^^^^

In any case, it would make no sense for a comparison operator to take non-const references.

like image 44
juanchopanza Avatar answered Oct 08 '22 18:10

juanchopanza