如何从C ++ std :: basic_ostream派生并使<<操作员虚拟的? [英] How to derive from C++ std::basic_ostream and make the << operator virtual?
问题描述
我正在编写一个具有各种消息输出的类.我想使此类与通用类和平台无关,因此我想对它传递 basic_ostream 引用,它可以将所有消息转储到流中.这样,如果在控制台程序中使用了该类,则可以将 std :: cout 传递给它并显示在控制台窗口中.
I am writing a class that has various messages output. I want to make this class general and platform independent, so I am thinking of passing a basic_ostream reference to it and it can dump all the messages into the stream. By doing this, if the class is used in a console program, I can pass std::cout to it and display in console window.
或者我可以将派生的ostream传递给它,然后将消息重定向到某些UI组件,例如列表框?唯一的问题是数据插入器operator <<
不是虚函数.如果我将派生类引用传递给它,则只有 basic_ostream <<运算符将被调用.
Or I could pass a derived ostream to it and redirect the message to some UI components, e.g. ListBox? The only problem is the data inserter operator <<
is not a virtual function. If I pass the derived class reference to it, only the basic_ostream << operator will be called.
有什么解决方法吗?
推荐答案
张楠自己的答案,最初是作为问题的一部分发布的:
跟进:好的,这是实现所需功能的派生std :: streambuf:
Follow up: OK, here is the derived std::streambuf that implements required functionality:
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_;
};
要使用此类,只需创建一个std :: ostream并使用此缓冲区初始化
To use this class just create a std::ostream and initialize with this buffer
std::ostream os(new listboxstreambuf(some_list_box_object));
这篇关于如何从C ++ std :: basic_ostream派生并使<<操作员虚拟的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!