I have written a template function like this:
template <class T>
const T& max1(const T& x, const T& y)
{
if(y < x)
return x;
return y;
}
Now, how can I use this function to compare two objects of class A where class A is like the following?
class A
{
public:
A(int x){i=x;}
private:
friend bool operator<(A const& lhs, A const& rhs)
{
return lhs.i < rhs.i;
}
int i;
};
I believe I have to overload < operator but could not figure out how this whole process is working? Could you also provide a link to articles where I can read about this?
Thank you.
Defining an overloaded
<operator is simple in this case:In general, defining overloaded operators is as simple as that (though if you want to access non-public members, you will need to
friendthe function within the class’s definition).Some operator overloads (like
[],(),=) cannot be defined as free functions, but instead must be member functions. This isn’t any harder than defining free-function overloaded operators, but is something to be aware of.