← 模式

重载 operator<<

1234567891011121314151617#include <iostream> class foo { public: friend std::ostream& operator<<(std::ostream& stream, foo const& f); private: int x = 10; }; std::ostream& operator<<(std::ostream& stream, foo const& f) { return stream << "A foo with x = " << f.x; }

此模式采用 CC0 公共领域贡献 许可。

要求 c++98 或更新版本。

意图

将您的类类型对象写入输出流。

描述

我们在 第 13-17 行实现了 operator<<,它接受一个对 std::ostream(所有输出流的基类)的引用,以及我们希望写入流的 foo 对象。在 第 16 行,我们简单地将一个表示 foo 对象的字符串写入流,并返回流本身的引用,从而允许链式调用。

请注意,我们在 第 6-7 行将这个 operator<< 声明为 foofriend(友元)。这使得它可以访问 foo 的私有成员 x

贡献者

  • Joseph Mansfield

最后更新

2017年12月9日

来源

在 GitHub 上 Fork 此模式

分享