Why it is possible to do
const string exclam = \"!\";
const string str = exclam + \"Hello\" + \" world\";
And not possible to do this:
The +
operator is left-associative (evaluated left-to-right), so the leftmost +
is evaluated first.
exclam
is a std::string
object that overloads operator+
so that both of the following perform concatenation:
exclam + "Hello"
"Hello" + exclam
Both of these return a std::string
object containing the concatenated string.
However, if the first two thing being "added" are string literals, as in:
"Hello" + "World"
there is no class type object involved (there is no std::string
here). The string literals are converted to pointers and there is no built-in operator+
for pointers.