"Hello"
不是一个std::string
(相反,它是一个const char[6]
, while ", "
is a const char[3]
)和+
运算符为std::string
s 不适用。
这是 C++ 的一个小不便,源于它的 C 血统。这意味着通过连接字符串+
您必须确保至少其中一项two操作数实际上是一个std::string
, as in
auto s = std::string{"Hello"} + ", " + "World";
第一个在哪里+
has a std::string
作为它的第一个操作数,因此产生一个std::string
,这样第二个+
还有一个std::string
作为它的第一个操作数(因为+
从左到右处理)。
Edit1评论提示T.C.,我提到如果仅用空格分隔,C 字符串文字会自动连接:
std::string s = "Hello" ", " "World";
这种行为也是从 C 继承的:预处理器将上面的代码呈现为
std::string s = "Hello, World";
在编译器正确处理它之前(更准确地说,字符串连接发生在phase 6翻译,就在编译之前)。事实上,这是连接原始字符串文字的最简单也是最方便的方法。但请注意,我必须声明类型s
, since auto
扣除会给出const char*
.
Edit2评论提示纸鸟大师,我提到从C++14开始,你可以直接形成std::string
只需添加文字即可s
在字符串之后,if你拉入相关的operator""s(或周围的命名空间)。
using std::literals::operator""s; // pull in required operator
const auto s = "Hello"s + ", " + "World"; // std::string
See 这个帖子至于为什么需要operator""s
隐藏在嵌套命名空间中。另请注意,或者using std::literals::operator""s;
你可以拉动周围的namespace
:以下任一声明都可以。
using namespace std::string_literals;
using namespace std::literals::string_literals;
using namespace std::literals;
这并不像普通的那么糟糕(而且该死)using namespace std;
.