为什么 cin 在包含字符串标头后接受字符串输入

Why cin accepts string inputs after including String header

本文关键字:字符串 输入 cin 包含 为什么      更新时间:2023-10-16

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

<string>定义函数

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>标头主要定义标准库的std::string类。没有它,你就没有字符串类C++:它不是语言的组成部分。当然,你可以使用char*字符串,C风格,但这不是我们通常在C++中做事的方式。

除了std::string,该标头还为std::string和流定义了>><<运算符,以便您可以执行诸如std::cout << my_stringstd::cin >> another_string之类的操作。该语法等效于operator<<(std::cout, my_string)operator>>(std::cin, another_string)

重要说明:C 语言的<string.h>标头与 C++ 的<string>完全不同。C 语言标头就像在 C 中一样可用,并定义了处理char*(以 null 结尾的(字符串的某些函数。不要混淆这两个标头,也不要混淆两种"字符串"。