How to overload cout behaviour in c++

2019-02-27 15:59发布

问题:

I would like to make cout will always print additional string(above and under) whenever I call it. It is actually weird to me cause I use in Java and C# primaly . EDIT: Maybe we can define other value for "y" string or something like that?

Example

code:

#include <iostream>
int main(){std::cout<<"y\n";}

result(printed):

x
y
z

I would not want to change int main() method just maybe overriding the << for the string type?

OR MAYBE make cout invoke additional method?

回答1:

I don't think you can do this with cout. What you can do instead is create a simple I/O wrapper that does your extra printing and then calls into cout to do the real work.