I want to overload the relational operators (<, >, <=, >=) as member functions but I can't seem to get it to work. I'm not sure how to access the calling member in the definition of the overload. I have tried the keyword this but I get an error saying that this can only be used in a nonstatic member function. How would I go about coding the definition? Thank you for your help.
When I try to access the member variables of my class it says that they are undefined. Here is my definition of the overload where "dollars" and "cents" are the member variables. They are declared as private but I don't see why that would be an issue since I am overloading the operator as a member function.
1 2 3 4 5 6 7 8 9
constbooloperator >(const Money& amount1) //Says there are too few arguments for the operator
{
if(dollars > amount1.getDollars()) returntrue; //This dollars is said to be undeclared
else
{
if (dollars == amount1.getDollars() && cents > amount1.getCents() returntrue; //This cents is the one that says is undeclared as well as the first dollars
elsereturnfalse;
};
}
The comments are the errors that I am getting. It seems to not like that there is only one operator in the definition and it doesn't like it when there are two operators in the declaration.
(I presume here that the method is also declared within the class body)
Andy
P.S. There is no need for a const when returning by value. Just return a bool, not a const bool. But you should have a const at the end of the function header.
@andywestken Well spotted, absolutely right. Needs to be const.
@ddwinters45
What you have there is not a member function declaration. For that you need to prefix the function name with the class scope:
1 2 3 4
/*const*/boolMoney::operator>(const Money& amount1) const // const goes after the parameters
{
// ...
}
The reason that the const goes after the parameters is because it is not the return value that is const but the whole function is const. That means that the function is not able to modify the object's member variables.