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

查看:36
本文介绍了如何从 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的公共接口是非虚拟的,那怎么做呢?我希望客户能够同时使用 operator<<并在 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 和语言环境,我建议你在继续之前先看看.

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天全站免登陆