1. 内置类型(如 int
, double
)的 >>
-
由
std::istream
的成员函数重载。 -
原因:
-
内置类型是语言原生支持的,标准库直接在其类内定义成员函数即可。
-
例如
std::cin >> n
实际上是调用std::istream::operator>>(int&)
。
-
示例代码(模拟实现)
cpp
class istream { public:// 成员函数重载 >> 用于内置类型istream& operator>>(int& val) {scanf("%d", &val); // 实际实现更复杂return *this;}istream& operator>>(double& val) {scanf("%lf", &val);return *this;} };
2. 自定义类型(如 std::string
, 用户自定义类)的 >>
-
通过全局友元函数重载。
-
原因:
-
自定义类型的
>>
需要访问该类的私有成员(如std::string
的缓冲区)。 -
如果定义为
std::istream
的成员函数,无法直接访问其他类的私有成员。 -
如果定义为自定义类的成员函数,调用方式会反直觉(如
str >> cin
)。
-
示例代码(标准库的 std::string
实现)
cpp
namespace std {template<typename CharT, typename Traits, typename Allocator>class basic_string {public:// 声明友元函数friend istream& operator>>(istream& is, basic_string& str);};// 全局函数定义template<typename CharT, typename Traits, typename Allocator>istream& operator>>(istream& is, basic_string<CharT, Traits, Allocator>& str) {str.clear();CharT ch;while (is.get(ch) && !isspace(ch)) {str.push_back(ch); // 访问私有成员}return is;} }
用户自定义类的实现示例
cpp
class Person { private:std::string name;int age; public:// 声明友元函数friend std::istream& operator>>(std::istream& is, Person& p); };// 全局函数定义 std::istream& operator>>(std::istream& is, Person& p) {is >> p.name >> p.age; // 访问私有成员return is; }
3. 关键对比
特性 | 内置类型的 >> | 自定义类型的 >> |
---|---|---|
重载位置 | std::istream 的成员函数 | 全局友元函数 |
访问权限 | 无需特殊权限(内置类型无私有成员) | 需友元声明以访问类的私有成员 |
调用方式 | cin >> n (cin.operator>>(n) ) | cin >> obj (operator>>(cin, obj) ) |
代表案例 | int , double , char | std::string , 用户自定义类 |