为什么 cin 在包含 String header 之后接受字符串输入

Why cin accepts string inputs after including String header

我是 C++ 编程新手。我试图接受用户输入并将它们放在一个变量中,我正在使用 cin 。它适用于除 strings 以外的整数和其他整数。所以,当我四处搜索时,我发现我必须包括 <string> header。我只是想了解,包含字符串 header 发生了什么变化?我认为 cin 被字符​​串 header 中定义的函数重载了。因此,我开始研究字符串 header,但我找不到 cin 重载或根本没有在其中定义的任何函数。谁能告诉我 cin 在包含 <string> 之后是如何开始接受字符串输入的?

<string> defines the functions

template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>& 
    operator<<(std::basic_ostream<CharT, Traits>& os, 
               const std::basic_string<CharT, Traits, Allocator>& str);

template <class CharT, class Traits, class Allocator>
std::basic_istream<CharT, Traits>& 
    operator>>(std::basic_istream<CharT, Traits>& is, 
               std::basic_string<CharT, Traits, Allocator>& str);

这些免费的标准库函数允许您将 std::string 用于任何从 basic_ostreambasic_istream 派生的流。

<string>header主要定义了标准库的std::stringclass。没有它,您将 在 C++ 中没有字符串 class:它不是语言的组成部分。当然,您可以使用 char*-strings,C-style,但这不是我们在 C++ 中通常做事的方式。

std::string 一起,header 还为 std::string 和流定义了 >><< 运算符,以便您可以做一些事情像 std::cout << my_stringstd::cin >> another_string。该语法等效于 operator<<(std::cout, my_string)operator>>(std::cin, another_string).

重要说明:C语言的<string.h>header与C++的<string>完全不同。 C语言header和C语言一样可用,定义certain functions working on char* (null-terminated) strings。不要混淆两个 header,也不要混淆两种 "strings".