5

さまざまなメッセージが出力されるクラスを作成しています。このクラスを一般的でプラットフォームに依存しないようにしたいので、basic_ostream参照を渡すことを考えています。これにより、すべてのメッセージをストリームにダンプできます。これにより、クラスがコンソール プログラムで使用されている場合、std::coutを渡してコンソール ウィンドウに表示できます。

または、派生した ostream をそれに渡し、メッセージをいくつかの UI コンポーネント (ListBox など) にリダイレクトできますか? 唯一の問題は、データ挿入operator <<機能が仮想関数ではないことです。派生クラスへの参照を渡すと、basic_ostream << 演算子のみが呼び出されます。

これに対する回避策はありますか?

4

1 に答える 1

1

もともと質問の一部として投稿されたNan Zhang自身の回答:

フォローアップ: OK、必要な機能を実装する派生 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));
于 2012-06-18T21:35:44.520 に答える