gpt4 book ai didi

c++ - 如何从 C++ std::basic_ostream 派生并使 << 运算符虚拟?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:49:13 26 4
gpt4 key购买 nike

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

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

有解决办法吗?

最佳答案

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));

关于c++ - 如何从 C++ std::basic_ostream 派生并使 << 运算符虚拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10301764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com