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

问题描述 投票:0回答:1
string s;
s += "#" + ',';  //give error
s += "#" + ",";  //give error
s += to_string(23) + ',';   //no error

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

c++ string concatenation push-back
1个回答
0
投票

问题在于

operator+
的优先级高于
operator+=
。这意味着
s += "#" + ','
等价于 写作

s += ("#" + ','); //same as 

现在,

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

本质上,这会在

const char*
上添加一个
int
。其结果用作
+=
的操作数。

© www.soinside.com 2019 - 2024. All rights reserved.