gpt4 book ai didi

c++ - C++ 怎么知道 "quotation marks"之间的任何东西是一个 std::string?

转载 作者:太空狗 更新时间:2023-10-29 19:56:34 24 4
gpt4 key购买 nike

这可能是题外话,因为没有代码,没有输出,什么都没有,但这里是。

我看到 C++ 可以知道 "this" 是一个 std::string 的唯一方法是因为引号是一种语言结构,很像 单引号之间的字符
但如果这是实际答案,我会感到非常惊讶:这是否意味着 std::string 是 C++ 必须解释引号之间文本的唯一方式?那么标准库就不仅仅是一个扩展,而是C++的一部分。
如果我想开发自己的 MyString 类,并且想使用引号即时创建 MyStrings 怎么办:我能做到还是 "" 语法不可避免地链接到 std::string?
我还想过 "" 是一个运算符(毕竟 C++ 有 operator()),但我找不到任何相关信息。

最佳答案

让我们澄清一些误解。字符串文字的类型是 const char[]不是 std::string。例如,"this" 的类型将是 const char[5](有一个空终止符)。

does that imply std::string is the only way C++ has to interpret text between quotation marks?

没有(它不是std::string),utf-8 字符串和宽字符串有多个前缀,比如L"wide"

then the standard lib would not be just an extension, but a part of C++.

确实如此,但对于字符串字面量而言则不然。您的 nullptr 类型是 std::nullptr_t。还有 std::byte 得到了标准的特殊处理。在使用列表初始化时选择一个 std::initializer_list 构造函数。 sizeof 的结果是一个 std::size_ttypeid 的结果是一个 std::type_info。可能还有其他我现在想不起来的。

would I be able to do it or is the "" syntax inevitably linked to the std::string?

它不是 std::string,但是,是的,那是不可能的。然而,你可以做的是定义一个 user-defined literal . std::string 有一个:

using namespace std::string_literals;
auto string = "this"s;

static_assert(std::is_same_v<decltype(string), std::string>); // ok

关于c++ - C++ 怎么知道 "quotation marks"之间的任何东西是一个 std::string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46513168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com