Overloading "<" operator

Hey guys I have this class of books that has two strings and I want to overload the "<" so that it checks firstly the book names and then the book authors

String _author
String _bookname


the thing is i have no idea how the eqution would look like but im pretty sure I should use ".compare"

Thanks!
Get a deck of cards.
Sort it according to the suit (clubs, hearts, spades, diamonds) and value (A to K)
Understand what you did
Translate that knowledge
so it goes something like this:

1
2
3
4
5
6
7
8
9
10
if(_author.compare(other._author)!=0){
{
  return _author<other._author;
}
    else if(_bookname.compare(other._bookname))!=0)
   {
        return _bookname<other._bookname;
   }
else return false;
}


Im not sure its the right way to behave tho

I tried this and seems to be working, but is this correct usage...

1
2
3
4
5
6
7
8
if(_surname.compare(o._surname)!=0){
  return true;
}
else if(_name.compare(o._name)!=0)
   {
        return true;
   }
	else return false;
Last edited on
Hmm... for overloading the < operator, it seems that the second code snippet is actually incorrect, simply because it's possible that _surname>o._surname. Same with name. It would be easily fixed by changing !=0 to <0.

Also, when you want to overload the < operator, how are you defining a<b?
im looking for same for same autho and then if they mismatch ie not eual since im comparing strings i go to the next one and check if they mismatch etc
Topic archived. No new replies allowed.