4、原始字面量

一、介绍 

  平时使用'\'去做转译,   在 C++11之后, 出现了原始字面量,定义方式为:R "xxx(原始字符串)xxx",表示括号里的字符串是原始的字符串,不需要做转译。其中()两边的字符串可以省略。当有时,两边必须相同。

二、使用

  案例1:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str = "D:\hello\world\test.text";
    cout << str << endl;
    string str1 = "D:\\hello\\world\\test.text";
    cout << str1 << endl;
    string str2 = R"(D:\hello\world\test.text)";
    cout << str2 << endl;

    return 0;
}

结果:

 

  案例2:在 C++11 之前如果一个字符串分别写到了不同的行里边,需要加连接符,这种方式不仅繁琐,还破坏了表达式的原始含义,如果使用原始字面量就变得简单很多,很强直观,可读性强。

  

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str = R"(<html>
        <head>
        <title>
        海贼王
        </title>
        </head>
        <body>
        <p>
        我是要成为海贼王的男人!!!
        </p>
        </body>
        </html>)";
    cout << str << endl;

    return 0;
}

 

posted @ 2021-07-25 23:44  zwj鹿港小镇  阅读(47)  评论(0编辑  收藏  举报