以下代码的输出使我困惑:
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";
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++
> S1: Mod
> S2: ern C++
有人能解释一下为什么吗?谢谢
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,它在被添加之前经历了更多的迭代)。它的界面实在太丰富了,你可能会碰到这样的东西;多个覆盖会导致混乱的结果。
string(char const*, count)
string(string const&, pos)
"this is not a std::string"
"this is a std string"s
std::string so_is="this";
std::string
bjg7j2ky2#
发件人:https://en.cppreference.com/w/cpp/string/basic_string/basic_string
使用以下构造函数:
basic_string( const CharT* s, size_type count, const Allocator& alloc = Allocator() );
basic_string( const CharT* s,
size_type count,
const Allocator& alloc = Allocator() );
所以需要3个字符 Mod .
Mod
将使用以下构造函数:
basic_string( const basic_string& other, size_type pos, const Allocator& alloc = Allocator() );
basic_string( const basic_string& other,
size_type pos,
从位置3开始取绳子,给出: ern C++ .
ern C++
2条答案
按热度按时间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,它在被添加之前经历了更多的迭代)。它的界面实在太丰富了,你可能会碰到这样的东西;多个覆盖会导致混乱的结果。
bjg7j2ky2#
发件人:
https://en.cppreference.com/w/cpp/string/basic_string/basic_string
使用以下构造函数:
所以需要3个字符
Mod
.将使用以下构造函数:
从位置3开始取绳子,给出:
ern C++
.