我在 C++17 草案 n4713 中遇到了这个代码片段:
#define R "x"
const char* s = R"y"; // ill-formed raw string, not "x" "y"
什么是“原始字符串”?它有什么作用?
原文由 S.S. Anne 发布,翻译遵循 CC BY-SA 4.0 许可协议
我将在其中一个评论中补充一个问题:
但在代码中,R 被定义为“x”,在扩展#define 之后,代码为 const char* s = “x”“y”;并且没有任何 R”(.
问题中的代码片段是显示原始字符串的无效使用。让我在这里获取实际的 3 行代码:
#define R "x"
const char* s = R"y"; // ill-formed raw string literal, not "x" "y"
const char* s2 = R"(a)" "b)"; // a raw string literal followed by a normal string literal
R"(x)"
你需要括号。R"_(a)" "b)_"
。 _
可以替换为任何字符(但不包括括号、反斜杠和空格)和任意数量的字符,只要其中不包含关闭序列: R"___(a)" "b)___"
或 R"anything(a)" "b)anything"
因此,如果我们将这些更正包装在一个简单的 C++ 代码中:
#include <iostream>
using namespace std;
#define R "x" // This is just a macro, not Raw String nor definition of it
const char* s = R"(y)"; // R is part of language, not a macro
const char* s2 = R"_(a)" "b)_"; // Raw String shall not include closing sequence of characters; )_"
int main(){ cout << s <<endl << s2 <<endl << R <<endl; }
那么输出将是
y
a)" "b
x
原文由 Yılmaz Durmaz 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
原始字符串文字是字符串文字,旨在更容易地包含嵌套字符,例如引号和反斜杠,这些字符通常具有分隔符和转义序列开头的含义。例如,它们对于编码 HTML 之类的文本很有用。例如,对比
这是一个常规的字符串文字,与
这是一个原始字符串文字。在这里,除了引号之外使用括号允许 C++ 将嵌套引号与分隔字符串本身的引号区分开来。