C++ 字符串串联
为什么可能这样做C++ 字符串串联,c++,string,C++,String,为什么可能这样做 const string exclam = "!"; const string str = exclam + "Hello" + " world"; 而且不可能做到这一点: const string exclam = "!"; const string str = "Hello" + " world" + exclam; 我知道(尽管不明白为什么)不允许这样做: const string str = "Hello" + " world" + "!"; 因为它将被解释为co
const string exclam = "!";
const string str = exclam + "Hello" + " world";
而且不可能做到这一点:
const string exclam = "!";
const string str = "Hello" + " world" + exclam;
我知道(尽管不明白为什么)不允许这样做:
const string str = "Hello" + " world" + "!";
因为它将被解释为
const char[6]+const char[6]+const char[1]
,所以从另一个角度来看,为什么这也是不允许的,或者为什么它使用char[]
而不是string
这是因为您正在压缩const char[6]
+const char[6]
,正如您所说,这是不允许的
<>在C++中,字符串文字(引号之间的东西)被解释为<代码> const char []/CODE> S.
您可以将
字符串
与常量char[]
连接起来(反之亦然),因为+
运算符在字符串中被重写,但对于基本类型它不能被重写。该+
运算符是左关联的(从左到右求值),因此首先求值最左边的+
感叹号
是一个std::string
对象,它重载运算符+
,以便以下两个对象都执行串联:
exclam + "Hello"
"Hello" + exclam
这两个函数都返回一个包含连接字符串的std::string
对象
但是,如果“添加”的前两项是字符串文字,如:
"Hello" + "World"
没有涉及类类型对象(这里没有std::string
)。字符串文字被转换为指针,指针没有内置的运算符+
const string exclam = "!"; // Initialize a c++ string with an ansi c string
const string str = exclam + "Hello" + " world"; // Using the operator+ method of exclam
您可以这样做,因为感叹号的运算符+
将返回一个包含“!Hello”的新字符串,您随后在该字符串上调用带有“world”参数的运算符+
,因此您将获得另一个字符串,该字符串最终通过复制构造函数分配给str
另一方面
const string str = "Hello" + " world" + exclam;
无法执行,因为“Hello”只是一个const char*
,它没有一个操作符+
将const char*
作为参数。(新答案,这在2010年是不可能的)
你现在可以写了
const string str = "Hello"s + " world"s + "!"s;
// ^ ^ ^
通过在字符串文本后添加
s
,可以告诉编译器它实际上是std::string
,而不是const char[]
。这意味着您可以在其上调用成员函数。例如,(“ABC”s).back()
,但也有+
除了解释你观察的原因的答案之外,我在这里发布了如何解决这个问题(你可能已经解决了这个问题)
替换
const string str = "Hello" + " world" + exclam;
与
因此,请确保第一个操作数是
字符串,而不是常量字符[]
@Philip:string literal的类型为常量字符[N]
,其中N
是字符串文本的大小。它是一个数组,与数组一样,它可以隐式转换为指向其第一个元素的指针(aconstchar*
)。在C++中,虽然字符串字符串的转换为(非<代码> const <代码> > <代码> char */COD>被禁止,但仍然允许。@ SBI:操作员永远不会得到评估,操作数。@ PrasOn:一个有效的NotrPoice,我不能做任何事情,因为我不能编辑该评论了。(然而,你没有回答我的隐含问题。)@sbi:这种操作符在英语中也被称为“左联想”。当我最初发表文章时,我不记得“X关联”是指“X-most”操作符是第一次计算还是最后一次计算(其中“X”是“左”还是“右”)。谢谢@普拉松:从技术上讲,表达式得到评估:-)谢谢,现在我肯定知道了!注意:我删除了我的评论,因为现在你已经把它加入到了你的答案中。如果你想连接字符串文字,那么不要使用+
:const string str=“Hello”“world”+感叹号代码>也仅对c++14有效
const string str = string("Hello") + " world" + exclam;