String concatenation

前端 未结 5 1189
暖寄归人
暖寄归人 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.

    0 讨论(0)
  • 2020-12-10 03:44

    In addition to the answers that explain the reason for your observations, I post here how to get rid of the problem (you might have figured this out already).

    Replace

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

    with

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

    so you make sure the first operand is a string and not a const char[].

    0 讨论(0)
  • 2020-12-10 03:49

    (New answer, this was not possible back in 2010)

    You can now write

    const string str = "Hello"s + " world"s + "!"s;
    //                        ^           ^      ^
    

    By adding that s after a string literal, you tell the compiler it's actually a std::string and not a const char[]. That means you can call members functions on it. E.g. ("ABC"s).back() but also +

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 04:04

    It's because you are concatanating const char[6] + const char[6], which is not allowed, as you said.

    In C++, string literals (stuff between quotes) are interpreted as const char[]s.

    You can concatenate a string with a const char[] (and vice-versa) because the + operator is overridden in string, but it can't be overridden for a basic type.

    0 讨论(0)
提交回复
热议问题