There are many explanations for how the compiler interprets this code, but what you probably wanted to know is what you did wrong.
It seems you are expecting + behavior from std::string . The problem is that none of the operands is actually std::string . C ++ considers operand types, not the final type of an expression (here the return type, std::string ), to allow overloading. He will not select std::string version + if he does not see std::string .
If you have special behavior for the operator (either you wrote it or got a library that provides it), this behavior is applicable only when at least one of the operands has a class type (or a reference to the class type and user settings) certain calculations transfers).
If you wrote
std::string("") + c
or
std::string() + c
or
""s + c
then you will get the std::string behavior of the + operator.
(Note: none of them is actually a good solution, because they all make short-lived instances of std::string , which can be avoided with std::string(1, c) )
The same goes for functions. Here is an example:
std::complex<double> ipi = std::log(-1.0);
You will get a runtime error instead of the expected imaginary number. This is because the compiler does not know that a complex logarithm should be used here. Overloading looks only at the arguments, and the argument is a real number (type double , in fact).
The operator overloads the ARE functions and follows the same rules.
Ben Voigt Sep 12 '14 at 17:31 2014-09-12 17:31
source share