加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么我可以构造一个包含多个字符串文字的字符串?

发布时间:2020-12-16 10:44:06 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why allow concatenation of string literals?????????????????????????????????????10个 #include iostream#include stringint main() { std::string str = "hello " "world" "!"; std::cout str;} 以下编译,运行和打印: hello world! see li
参见英文答案 > Why allow concatenation of string literals?????????????????????????????????????10个

#include <iostream>
#include <string>

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

以下编译,运行和打印:

hello world!

see live

似乎字符串文字被连接在一起,但有趣的是,这不能用运算符完成:

#include <iostream>
#include <string>

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

这将无法编译.
see live

为什么这种行为在语言中?我的理论是允许字符串用多个#include语句构造,因为#include语句需要在它们自己的行上.由于语言的语法,这种行为是否可行,或者是为了帮助解决问题而添加的异常?

解决方法

相邻的字符串文字是连接的,我们可以在 draft C++ standard部分中看到这一点.2.2翻译阶段第6段说:

Adjacent string literal tokens are concatenated

在你的另一种情况下,没有定义operator+采取两个* const char **.

至于为什么,这来自C,我们可以转到Rationale for International Standard—Programming Languages—C,它在第6.4.5节中说明了字符串文字:

A string can be continued across multiple lines by using the backslash–newline line continuation,but this requires that the continuation of the string start in the first position of the next line. To permit more flexible layout,and to solve some preprocessing problems (see §6.10.3),the C89 Committee introduced string literal concatenation. Two string literals in a row are pasted together,with no null character in the middle,to make one combined string literal. This addition to the C language allows a programmer to extend a string literal beyond the end of a physical line without having to use the backslash–newline mechanism and thereby destroying the indentation scheme of the program. An explicit concatenation operator was not introduced because the concatenation is a lexical construct rather than a run-time operation.

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

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

这很难看.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读