我刚看到一个新的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)
| 归档时间: |
|
| 查看次数: |
146 次 |
| 最近记录: |