• 【1】c++11新特性(稳定性和兼容性)—>原始字面量


    在C++11中添加了定义原始字符串的字面量,定义方式为:R “xxx(原始字符串)xxx”其中()两边的字符串可以省略。原始字面量R可以直接表示字符串的实际含义,而不需要额外对字符串做转义或连接等操作。
    编程过程中,使用的字符串中常带有一些特殊字符,对于这些字符往往要做专门的处理,使用了原始字面量就可以轻松的解决这个问题了,比如打印路径:

    #include
    #include
    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    R"(D:\hello\world\test.text)"使用了原始字面量R()中的内容就是描述路径的原始字符串,无需做任何处理.
    再看一个输出HTML标签的例子:

    #include
    #include
    using namespace std;
    int main()
    {
    #if 0
        string str = "\
            \
            \
            海贼王\
            \
            \
            \
            

    \ 我是要成为海贼王的男人!!!\

    \ \ "
    ; cout << str << endl; #else if //新特性 string str = R"( 海贼王

    我是要成为海贼王的男人!!!

    )"
    ; cout << str << endl; #endif return 0; }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    最后强调一个细节:在R “xxx(raw string)xxx” 中,原始字符串必须用括号()括起来,括号的前后可以加其他字符串,所加的字符串会被忽略,并且加的字符串必须在括号两边同时出现。

    #include
    #include
    using namespace std;
    int main()
    {
        string str1 = R"(D:\hello\world\test.text)";
        cout << str1 << endl;
        string str2 = R"luffy(D:\hello\world\test.text)luffy";
        cout << str2 << endl;
    #if 0
        string str3 = R"luffy(D:\hello\world\test.text)robin";	// 语法错误,编译不通过
        cout << str3 << endl;
    #endif
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    通过输出的信息可以得到如下结论:使用原始字面量R “xxx(raw string)xxx”,()两边的字符串在解析的时候是会被忽略的,因此一般不用指定。如果在()前后指定了字符串,那么前后的字符串必须相同,否则会出现语法错误。

  • 相关阅读:
    MySQL实现事务隔离的原理
    input禁止输入
    酷开科技 | 酷开系统大屏电视,打造精彩家庭场景
    图论:自反与对称
    vue的移动端项目打包成手机的app软件apk格式
    git提交错了?别慌,直接删除提交记录
    开发微信小程序消息订阅的步骤
    Java—反射
    PHP MySQL 交互 笔记/练习
    酷克数据发布HD-SQL-LLaMA模型,开启数据分析“人人可及”新时代
  • 原文地址:https://blog.csdn.net/weixin_42097108/article/details/133849518