以下代码的输出让我感到困惑:
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";
Run Code Online (Sandbox Code Playgroud)
输出:
> S1: Mod
> S2: ern C++
Run Code Online (Sandbox Code Playgroud)
谁能解释这个结果?
0RR*_*0RR 66
从:
https://en.cppreference.com/w/cpp/string/basic_string/basic_string
std::string s1 {"Modern C++", 3};
Run Code Online (Sandbox Code Playgroud)
使用以下构造函数:
basic_string( const CharT* s,
size_type count,
const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)
所以需要 3 个字符才能得到Mod.
std::string s2 {str, 3};
Run Code Online (Sandbox Code Playgroud)
将使用以下构造函数:
basic_string( const basic_string& other,
size_type pos,
const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)
所以从位置 3 开始取字符串给 : ern C++。
Yak*_*ont 35
一个是打电话string(char const*, count),另一个string(string const&, pos)。
一个从缓冲区中获取前 3 个字符,另一个获取第 3 个字符之后的所有字符。
这是因为 C++ 具有原始字符缓冲区和标准字符串。 "this is not a std::string". "this is a std string"s, std::string so_is="this";.
std::string 已有30多年的历史,并且在没有足够小心的情况下被添加到C++语言中(与STL不同,它在添加之前经历了更多的迭代)。
老实说,它的界面太丰富了,你可能会遇到这样的东西;导致混乱结果的多个重载。
谁能向我解释这是为什么?
那是因为std::string有它不应该的构造函数(@ORR解释了细节)。它不应该有这些构造函数,因为:
std::string方法和现有构造函数可以轻松实现它们的效果- 无需额外成本(至少在 C++11 中),并且这不是标准库中具有这种不良(恕我直言)构造函数的唯一情况;std::vector因构造函数种类繁多和令人困惑/误导性的构造函数语义而(臭名昭著)。
人生课程: