簡體   English   中英

如何在std :: stringstream的后代中在“ this”上調用operator <<?

[英]How to call operator<< on “this” in a descendant of std::stringstream?

class mystream : public std::stringstream
{
public:
    void write_something()
    {
        this << "something";
    }
};

這導致在VC ++ 10上出現以下兩個編譯錯誤:

error C2297: '<<' : illegal, right operand has type 'const char [10]'
error C2296: '<<' : illegal, left operand has type 'mystream *const '

從第二個來看,這是因為不能更改 this指向的內容,但是<<操作符可以更改(或至少聲明為好像更改)。 正確?

有一些其他辦法,我仍然可以使用<<>>運營商this

mystream *const表示this是指向非常量對象的常量指針。 問題是您試圖將流插入到指針中-您必須插入到流中。 嘗試以下方法。

*this << "something";

basic_stringstream<char>的析構函數(實際上是basic_stringstream<char> )不是虛擬的,而且由於C ++ SL中的所有類,您實際上都不應該從它們派生...

根據您要確切執行的操作,我將告訴您更喜歡使用組合而不是繼承,並可能創建自己的模板<<和>>運算符,這些運算符將使用基礎流。 也許不使用字符串流作為成員更為明智。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM