这个新的c ++语法的名称是什么?

dgu*_*uan 2 c++ c++11 c++17

我刚看到一个新的C++语法,如:

x = "abc"s;
Run Code Online (Sandbox Code Playgroud)

从上下文我猜测这意味着x被分配了一个字符串"abc",我想知道这个新语法的名称,并且在C++ 1z中是否有任何类似的语法?

Ale*_*agh 11

是的,他们自C++ 11以来一直存在.它们被称为用户定义的文字.这个特定的文字是在C++ 14中标准化的,但是很容易推出自己的文字.

#include <string>
#include <iostream>

int main()
{
    using namespace std::string_literals;

    std::string s1 = "abc\0\0def";
    std::string s2 = "abc\0\0def"s;
    std::cout << "s1: " << s1.size() << " \"" << s1 << "\"\n";
    std::cout << "s2: " << s2.size() << " \"" << s2 << "\"\n";
}
Run Code Online (Sandbox Code Playgroud)

例如,要创建自己的std :: string文字,您可以这样做(注意,所有用户定义的文字都必须以下划线开头):

std::string operator"" _s(const char* s, unsigned long n)
{
    return std::string(s, n);
}
Run Code Online (Sandbox Code Playgroud)

要使用我给出的示例,只需执行以下操作:

#include <iostream>
#include <string>

std::string operator"" _s(const char* s, unsigned long n)
{
    return std::string(s, n);
}


int main(void)
{
    auto s = "My message"_s;
    std::cout << s << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 或许将"添加"替换为"标准化"?:可以在C++ 11中自行完成. (2认同)
  • @Bathsheba可以吗?我认为所有用户定义的文字都必须以`_`开头? (2认同)
  • @Curious:你说的没错.(就个人而言,我认为用户定义的文字只是标准委员会的一种放纵.我们是否真的*需要这个,例如以模块为代价?) (2认同)