[英]Why "+=" operator not works when more than one string is added?
when I'm trying to concatenate a string variable with more than one string with this operator(+=) it rises an error.当我尝试使用此运算符 (+=) 连接一个字符串变量与多个字符串时,它会引发错误。
NOTE: The other two strings should not be stored in a variable.注意:其他两个字符串不应存储在变量中。
string str="hello";
str = str + " " + "world";
cout << str << endl; //hello world
str += " " + "world";
cout << str; //error //why?
//*but in java it works*
Because you're trying to add two string literals.因为您要添加两个字符串文字。 The expression:
表达方式:
" " + "world"
in C++ is of type在 C++ 是类型
const char* + const char*
const char*
has no overloaded operator+. const char*
没有重载的 operator+。 But standard strings do overload operator+ for addition with string literals, eg:但是标准字符串确实会重载 operator+ 以与字符串文字相加,例如:
operator+(std::string const& lhs, const char *rhs);
and that's why your first expression succeeds: the str
object gets the ball rolling:这就是您的第一个表达式成功的原因:
str
object 让球滚动:
str + " " + "World"
= std::string + const char* + const char*
= std::string + const char*
= std::string
to make it work use让它工作使用
str += " world"
// or
str += std::string(" ") + "world";
// the last one is to better explain what's going on,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.