以下代码的输出使我感到困惑:
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++有人能解释这个结果吗?
发布于 2021-01-01 22:43:38
发自:
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++。
发布于 2021-01-01 22:44:00
一个叫string(char const*, count),另一个叫string(string const&, pos)。
一个从缓冲区中获取前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不同,它在添加之前经历了更多的迭代)。
它的界面实在太丰富了,您可能会遇到这样的情况:多个重载会导致令人困惑的结果。
发布于 2021-01-02 22:14:21
有人能解释一下为什么吗?
这是因为std::string有它不应该使用的构造函数(@ORR 解释 the details)。它不应该有这些构造函数,因为:
std::string方法和现有的构造函数可以轻松地实现它们的效果--不需要额外的成本(至少在C++11中),以及这并不是标准库中仅有的具有这种可扩展(IMHO)构造函数的情况;std::vector以构造函数种类过多和混淆/误导性构造函数语义而闻名。
生活课程:
https://stackoverflow.com/questions/65534293
复制相似问题