首页 > 解决方案 > std::string s1 {"现代 C++", 3} 与 std::string s1 {str, 3}

问题描述

以下代码的输出让我感到困惑:

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++

谁能解释这个结果?

标签: c++stringc++17

解决方案


从:

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++


推荐阅读