为什么我可以用多个字符串文字构造一个字符串

为什么我可以用多个字符串文字构造一个字符串

本文介绍了为什么我可以用多个字符串文字构造一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <string>

int main() {
    std::string str = "hello " "world" "!";
    std::cout << str;
}

以下编译,运行和打印:

The following compiles, runs, and prints:

好像字符串文字被串联在一起,但是有趣的是,这不能用 operator + 来完成:

It seems as though the string literals are being concatenated together, but interestingly this can not be done with operator +:

#include <iostream>
#include <string>

int main() {
    std::string str = "hello " + "world";
    std::cout << str;
}

这将无法编译。

为什么这种行为是该语言的?我的理论是,它允许使用多个 #include 语句构造字符串,因为必须使用 #include 语句自己行。

Why is this behavior in the language? My theory is that it is allows strings to be constructed with multiple #include statements because #include statements are required to be on their own line. Is this behavior simply possible due to the grammar of the language, or is it an exception that was added to help solve a problem?

推荐答案

相邻的字符串文字已连接在一起,我们可以在部分 2.2 翻译阶段 6 段,其中:

Adjacent string literals are concatenated we can see this in the draft C++ standard section 2.2 Phases of translation paragraph 6 which says:

在其他情况下,没有定义来定义两个* const char **。

In your other case, there is no operator+ defined to take two *const char**.

为什么,这来自 C ,我们可以转到国际标准理论(编程语言)C 并在 6.4.5 字符串文字部分中说:

As to why, this comes from C and we can go to the Rationale for International Standard—Programming Languages—C and it says in section 6.4.5 String literals:

如果没有此功能,您会必须执行以下操作才能在多行上继续字符串文字:

without this feature you would have to do this to continue a string literal over multiple lines:

   std::string str = "hello \
world\
!";

这很丑。

这篇关于为什么我可以用多个字符串文字构造一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:35