我想将更多字符和字符串连接到 C++ 中的现有字符串

0 c++ string concatenation push-back

string s;
s += "#" + ',';  //give error
s += "#" + ",";  //give error
s += to_string(23) + ',';   //no error
Run Code Online (Sandbox Code Playgroud)

使用 + 运算符将新字符和字符串连接到现有字符串的正确方法是什么?什么时候会抛出错误?有人还可以阐明append()和push_back()与“+”有何不同以及哪种是最佳方式吗?

use*_*570 7

情况1

下面我们考虑一下这个说法s += "#" + ',';

问题是 的operator+优先高于operator+=. 这意味着s += "#" + ','相当于

s += ("#" + ','); //same as s += "#" + ','
Run Code Online (Sandbox Code Playgroud)

现在,"#"是类型的字符串文字const char [2],而','是类型的字符文字char。所以基本上,在这种情况下,您尝试将字符串文字添加到 char。现在,当您执行此操作时,字符串文字会衰减为 aconst char*并且字符文字会提升为int

本质上,这将 a 添加const char*int。其结果用作 的操作数+=

有关此内容的更多信息,请参阅C++ 将字符串文字添加到字符文字


案例2

下面我们考虑一下这个说法s += "#" + ",";

在这种情况下,该语句也s += "#" + ",";相当于编写

s += ("#" + ","); //same as s += "#" + ","
Run Code Online (Sandbox Code Playgroud)

由于运算符优先级

但在这种情况下,两个操作数 operator+ 都是类型 const char [2]

所以本质上,您试图在此处添加两个字符串文字。但是没有重载operator+需要两个字符串文字,const char*所以这会给出上述错误:

 error: invalid operands of types 'const char [2]' and 'const char [2]' to binary 'operator+'
Run Code Online (Sandbox Code Playgroud)

解决方案

有多种方法可以解决此问题,其中包括s在字符串文字后添加后缀,如下所示:

using namespace std::string_literals;
s += "#"s + ","s;  //works correctly now
Run Code Online (Sandbox Code Playgroud)

另一种方法是显式地编写std::string("#").

  • 所以,如果你无法避免它,就写```s += std::string("#") + ",";```。这样,您就可以将 const char* "," 连接到已定义的 std::string 。 (2认同)