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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With