String concatenation

前端 未结 5 1196
暖寄归人
暖寄归人 2020-12-10 03:22

Why it is possible to do

const string exclam = \"!\";
const string str = exclam + \"Hello\" + \" world\";

And not possible to do this:

5条回答
  •  春和景丽
    2020-12-10 04:04

    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.

提交回复
热议问题