Nan Zhang自己的答案,最初作为问题的一部分发布:
跟进:好的,这是实现所需功能的派生 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_;
};
要使用此类,只需创建一个 std::ostream 并使用此缓冲区进行初始化
std::ostream os(new listboxstreambuf(some_list_box_object));