如何从C++ std :: basic_ostream派生并使<< operator virtual?

Nan*_*ang 5 c++ iostream std stream

我正在写一个有各种消息输出的类.我想使这个类具有通用性和平台独立性,所以我想将一个basic_ostream引用传递给它,它可以将所有消息转储到流中.通过这样做,如果在控制台程序中使用该类,我可以将std :: cout传递给它并显示在控制台窗口中.

或者我可以将派生的ostream传递给它并将消息重定向到某些UI组件,例如ListBox?唯一的问题是数据插入器operator <<不是虚函数.如果我将派生类引用传递给它,则只会调用basic_ostream <<运算符.

这有什么解决方法吗?

Bo *_*son 3

张楠自己的回答,最初作为问题的一部分发布:

跟进:好的,这是实现所需功能的派生 std::streambuf:

class listboxstreambuf : public std::streambuf { 
public:
    explicit listboxstreambuf(CHScrollListBox &box, std::size_t buff_sz = 256) :
            Scrollbox_(box), buffer_(buff_sz+1) {
        char *base = &buffer_.front();
        //set putbase pointer and endput pointer
        setp(base, base + buff_sz); 
    }

protected:
    bool Output2ListBox() {
        std::ptrdiff_t n = pptr() - pbase();
        std::string temp;
        temp.assign(pbase(), n);
        pbump(-n);
        int i = Scrollbox_.AddString(temp.c_str());
        Scrollbox_.SetTopIndex(i);
        return true;
    }

private:
    int sync() {
        return Output2ListBox()? 0:-1;
    }

    //copying not allowed.
    listboxstreambuf(const listboxstreambuf &);
    listboxstreambuf &operator=(const listboxstreambuf &);

    CHScrollListBox &Scrollbox_;
    std::vector<char> buffer_;
};
Run Code Online (Sandbox Code Playgroud)

要使用此类,只需创建一个 std::ostream 并使用此缓冲区进行初始化

std::ostream os(new listboxstreambuf(some_list_box_object));
Run Code Online (Sandbox Code Playgroud)