String concatenation

前端 未结 5 1205
暖寄归人
暖寄归人 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 03:43

    const string exclam = "!";    // Initialize a c++ string with an ansi c string
    const string str = exclam + "Hello" + " world"; // Using the operator+ method of exclam
    

    You can do it because the operator+ of exclam will return a new string containing "!Hello", on which you subsequently call the operator+ with " world" as parameter, so you get another string which, finally, gets assigned to str by means of the copy constructor.

    On the other hand

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

    cannot be executed because "Hello" is just a const char *, which doesn't have a operator+ taking a const char * as parameter.

提交回复
热议问题