What does the syntax " bool Operator < " mean in C++?

Asked

Viewed 168 times

0

I looked for that reference (bool operator < and bool operator ==), I found some explanations, but I didn’t understand it very well. How this syntax works?

Code:

bool operator < (nome a, nome b){
   return a.idade < b.idade;
}

bool operator == (nome a, nome b){
   return a.idade == b.idade;
}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

This is an operator’s declaration. C++ allows operator overload. Then you can write the code with the operator’s behavior for certain types. In the background you are creating a function that will be executed when you find that operator being with this type. Of course, the function does not necessarily need to be called since the code is usually very simple and there will probably be an optimization that will place its code directly where it was used (inline Optimization).

This is part of the job signature. Obviously you need the keyword operator to differentiate from a normal function and the compiler does not get confused with the syntax and helps to become more readable.

In this example you are demonstrating how to compare two objects of the type nome and that the age of each object should be taken to compare and tell whether it is less or equal in the other. It’s probably a bit of a meaningless code, so understand the mechanism but don’t do as you saw it somewhere.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.