std::string s1{“现代c++”,3}与std::string s1{str,3}

zazmityj  于 2021-06-26  发布在  Hive
关注(0)|答案(2)|浏览(306)

以下代码的输出使我困惑:

const std::string str = "Modern C++";

std::string s1 {"Modern C++", 3};
std::string s2 {str, 3};

std::cout << "S1: " << s1 << "\n";
std::cout << "S2: " << s2 << "\n";

输出:

> S1: Mod
> S2: ern C++

有人能解释一下为什么吗?谢谢

bqf10yzr

bqf10yzr1#

一个在打电话 string(char const*, count) ,另一个 string(string const&, pos) .
一个从缓冲区获取前3个字符,另一个从第3个字符之后获取所有字符。
这是因为c有原始字符缓冲区和std字符串。 "this is not a std::string" . "this is a std string"s , std::string so_is="this"; . std::string 它已经有30多年的历史了,而且它是在没有足够注意的情况下被添加到c语言中的(不像stl,它在被添加之前经历了更多的迭代)。
它的界面实在太丰富了,你可能会碰到这样的东西;多个覆盖会导致混乱的结果。

bjg7j2ky

bjg7j2ky2#

发件人:
https://en.cppreference.com/w/cpp/string/basic_string/basic_string

std::string s1 {"Modern C++", 3};

使用以下构造函数:

basic_string( const CharT* s,
          size_type count,
          const Allocator& alloc = Allocator() );

所以需要3个字符 Mod .

std::string s2 {str, 3};

将使用以下构造函数:

basic_string( const basic_string& other,
          size_type pos,
          const Allocator& alloc = Allocator() );

从位置3开始取绳子,给出: ern C++ .

相关问题