如何从std :: ostream继承? [英] How to inherit from std::ostream?

查看:150
本文介绍了如何从std :: ostream继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在谷歌上搜索,我找不到一个简单的答案。它应该很简单,因为STL通常是。

I've been googling around and I just can't find a simple answer to this. And it should be simple, as the STL generally is.

我想定义从std :: ostream公开继承的MyOStream。假设我想在每次将某些内容写入流中时调用foo()。

I want to define MyOStream which inherits publicly from std::ostream. Let's say I want to call foo() each time something is written into my stream.

class MyOStream : public ostream {
public:
  ...
private:
   void foo() { ... }
}

我知道ostream的公共接口是非虚拟的,那怎么办呢?
我希望客户能够同时使用运营商<<并且在MyOStream上使用write()和put()并使用我班级的扩展能力。

I understand that the public interface of ostream is non-virtual, so how can it be done? I want clients to be able to use both operator<< and write() and put() on MyOStream and have use the extended ability of my class.

推荐答案

这不是一个简单的问题,不幸的是。您应该派生的类是 basic _ 类,例如 basic_ostream 。但是,从流中派生可能不是您想要的,您可能希望从流缓冲区派生,然后使用此类来实例化现有流类。

It's not a simple question, unfortunately. The classes you should derive from are the basic_ classes, such as basic_ostream. However, derivation from a stream may not be what you want, you may want to derive from a stream buffer instead, and then use this class to instantiate an existing stream class.

整个区域都很复杂,但有一本很好的书籍标准C ++ IOStreams和Locales ,我建议你在继续之前先看一下。

The whole area is complex, but there is an excellent book about it Standard C++ IOStreams and Locales, which I suggest you take a look at before going any further.

这篇关于如何从std :: ostream继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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