欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > >>流提取运算符重载

>>流提取运算符重载

2025/5/4 20:06:42 来源:https://blog.csdn.net/An15294874732/article/details/147678458  浏览:    关键词:>>流提取运算符重载

1. 内置类型(如 intdouble)的 >>

  • 由 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 >> ncin.operator>>(n)cin >> objoperator>>(cin, obj)
代表案例intdoublecharstd::string, 用户自定义类

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词