简体   繁体   English

ostream 重载中的缓冲区刷新

[英]Buffer flushing in ostream overloading

What is the recommended way to use buffer flushing when overloading ostream in C++?在 C++ 中重载 ostream 时,推荐使用缓冲区刷新的方法是什么? Do I just disable buffer flushing in the beginning and enable it in the end?我是否只是在开始时禁用缓冲区刷新并在最后启用它? If so should i flush the buffer before returning the ostream?如果是这样,我应该在返回 ostream 之前刷新缓冲区吗? I have never seen this part mentioned in any ostream overloading reference.我从未在任何 ostream 重载参考中看到过这部分。 EDIT: Lets say i have a class with a lot of members.编辑:假设我有一个有很多成员的班级。 The ostream operator prints each member. ostream 运算符打印每个成员。 How should i write the ostream overload?我应该如何编写 ostream 重载?

struct ToPrint {
char firstMember;
char secondMember;
int number;
};

std::ostream& operator<<(std::ostream& os, const ToPrint& instance) {
    os << instance.firstMember << '\n'
        << instance.secondMember << '\n';
    if (instance.number > 0)
        os << instance.number << '\n';
    return os;
}

The recommended use of buffer flushing for output streams in C++ is to not do it. C++ 中输出流的缓冲区刷新的推荐使用是不要这样做。 Unless you have special requirements, the default behavior of the stream will work just fine.除非您有特殊要求,否则流的默认行为将正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM