I’m trying to understand operators in C++ more carefully.
I know that operators in C++ are basically just functions. What I don’t get is, what does the function look like?
Take for example:
int x = 1;
int y = 2;
int z = x + y;
How does the last line translate? Is it:
1. int z = operator+(x,y);
or
2. int z = x.operator+(y);?
When I tried both of them, the compiler errors. Am I calling them wrong or are operators in C++ not allowed to be called directly?
Using C++ standardese, the function call syntax (
operator+(x, y)orx.operator+(y)) works only for operator functions:And operator functions require at least one parameter that is a class type or an enumeration type:
That implies that an operator function
operator+()that only takesints cannot exist per 13.5/6. And you obviously can’t use the function call syntax on an operator function that can’t exist.