我什么时候应该返回 std::ostream
When should I return std::ostream?
每次我要创建一个像运算符这样的运算符std::string
以显示值(没有运算符)时,我都会返回std::ostream
,但我不知道为什么。如果std::ofstream
用作函数成员运算符函数(std::cout
),我该如何返回它,我应该什么时候返回,为什么?
例:
class MyClass
{
int val;
std::ostream& operator<<(const std::ostream& os, const MyClass variable)
{
os << variable.val;
}
}
std::string
:
std::string a("This is an example.");
std::cout << a;
通常在重载<<
时返回对ostream
的引用,以允许链接。这:
s << a << b;
等效于函数调用
operator<<(operator<<(s,a),b);
并且仅在内部调用返回合适的类型作为外部调用的参数时才有效。
要实现这一点,只需通过引用获取流参数,并通过引用直接返回相同的流:
std::ostream & operator<<(std::ostream & s, thing const & t) {
// stream something from `t` into `s`
return s;
}
或从其他重载返回:
std::ostream & operator<<(std::ostream & s, thing const & t) {
return s << t.whatever();
}
相关文章:
- boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为
- 与'operator<<'不匹配(操作数类型'std::ostream {aka std::basic_ostream<char>}'
- 与"operator<<"不匹配(操作数类型'std::ostream'
- 运算符的歧义错误<<自定义 std::ostream 子类中的重载
- 关于 std::ostream 构造函数
- STD :: Ostream忽略了通过setf()在基础上设置的十六进制标志
- 将 std::ostream 转换为 std::string
- STD :: Ostream:类是不可接受的[C ]
- 为什么在三元运算符中使用STD :: Ostream不会编译
- 当我编译引用 std::ostream 时,我有一个奇怪的错误弹出
- 如何跟踪写入std :: Ostream对象的字节数
- std::ostream的下降表达(针对SFINAE)
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 我什么时候应该返回 std::ostream
- 如何移动std::ostream
- 如何在自定义 std::ostream 类中使用 std::endl
- 如何清除std::ostream
- 返回对此的引用时出现意外的std::ostream输出
- std::ostream to QDataStream
- 使用 std::ostream 方法将格式化文本输出到 std::string 对象