如何在C ++中重载cout行为 [英] How to overload cout behaviour in c++

查看:380
本文介绍了如何在C ++中重载cout行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让cout每次调用时都将始终打印其他字符串(上下).实际上,这对我来说很奇怪,因为我最初在Java和C#中使用它. 也许我们可以为"y"字符串或类似的东西定义其他值?

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 . Maybe we can define other value for "y" string or something like that?

示例

代码:

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

结果(打印):

x
y
z

我不想更改int main()方法,只是想覆盖字符串类型的<<吗?

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

或可能 使cout调用其他方法?

OR MAYBE make cout invoke additional method?

推荐答案

我认为您不能使用cout做到这一点.相反,您可以做的是创建一个简单的I/O包装器,进行额外的打印,然后调用cout进行实际工作.

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.

这篇关于如何在C ++中重载cout行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆