添加字符串和文字,顺序如何影响是否可以正确添加字符串
Adding strings and literals, how does the order affect if you can add the strings without error
请考虑以下字符串定义:
string s1 = "hello", s2 = "world";
string s6 = s1 + ", " + "world";
string s7 = "hello" + ", " + s2;
C++ Primer 5e 的书指出,第三行将导致编译器给出错误,因为您无法添加字符串文字。编译器给出的实际错误是
error: invalid operands of types 'const char [6]'
and 'const char [3]' to binary 'operator+'
但是第二个字符串s6
不是和s7
做完全相同的事情吗?有什么区别?
由于加法从左到右关联,因此s6
被解析为(s1 + ", ") + "world"
。 这会给const char *
增加一个string
,导致另一个string
。 然后我们向该string
添加另一个const char *
,从而产生存储在s6
中的第三个string
。
s7
被解析为("hello" + ", ") + s2
,它试图将一个const char *
添加到另一个const char *
,这是你不能做的。 您可以将其重写为 "hello" + (", " + s2)
然后进行编译。
相关文章:
- 如何将字符串添加到布谷鸟过滤器?
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 如何在C++中为字符串添加字符?
- 在特定位置为字符串添加空格
- 有没有办法将字符串添加到 Vector 中,但前提是它尚不存在?->C++
- 是什么使这个以'+'开头的字符串添加成为有效的语句?
- 如何使用函数将字符串添加到向量中
- 如何在 c++ 中将字符串添加到动态数组?
- 向字符串添加字符
- 向字符串添加位值
- 如何从用户那里接收多个字符串并将这些字符串添加到 c++ 中的数组中?
- 字符串添加数字 C++
- std::字符串添加到字符*
- C++ 向字符串添加"u"
- JSONCPP正在向字符串添加额外的双引号
- C 将N字符串添加到字符串流中
- 以简单且更少的代码方式将字符串添加在一起
- 字符串添加或减法操作员
- 将字符串添加到2D数组并显示COUT消息(没有错误消息?)的错误
- 如何使用递归向字符串添加逗号