C++ 输入输出流的 operator

270 字
1 分钟
C++ 输入输出流的 operator

今天是朝鲜主体历114年5月14日 (喜)

说正事,马上就到期末周了,C++ 已经结课有一段时间了,这两天在复习 C++ 的基础知识。复习到运算符重载,我发现对输入输出流的重载都用友元函数,记得当时学的时候就有点疑惑,但是也没有深究。现在有时间了,我好好研究了一下。

为什么不能用普通成员函数?#

当运算符重载为成员函数时,this指针会被隐式绑定到左操作数。例如:

class A {
public:
bool operator==(const A& rhs) const; // 等价于 bool A::operator==(const A* this, const A& rhs)
};
a == b; // 实际调用 a.operator==(b), 即 operator==(&a, b)

因此,成员函数重载的运算符左操作数必须是类的实例。但流运算符的左操作数是std::ostream/std::istream,这与成员函数的绑定规则冲突。

显而易见,使用友元函数是最优解。

class Person {
private:
std::string name;
public:
friend std::ostream& operator<<(std::ostream&, const Person&);
};
std::ostream& operator<<(std::ostream& os, const Person& p) {
os << p.name;
return os;
}

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

C++ 输入输出流的 operator
https://blog.blackcyan.top/posts/cpp-io-operator/
作者
墨青BlackCyan
发布于
2025-05-14
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
墨青BlackCyan
三点几了,饮茶先啦
公告
欢迎来到墨青的博客!
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
分类
标签
站点统计
文章
12
分类
2
标签
25
总字数
7,351
运行时长
0
最后活动
0 天前
站点信息
构建平台
Local
博客版本
Firefly v6.13.10
文章许可
CC BY-NC-SA 4.0