2016-01-13 65 views
0

代碼:
ostream的運營商<<調用父ostream的

cout << "11122333" << endl; 

期待:
11122333 \ n
結果:
11122333 \ n
所有權利。
代碼:

cout.operator<<("11122333"); 
cout.operator<<(endl); 

期待:
11122333 \ n
結果:
00B273F8 \ n
(或其他地址,它轉換爲void* :()

麻煩: 想要寫出來的類從ostream

class SomeStream : public ostream 
{ 
    public: 
    explicit SomeStream(streambuf* sb) : ostream(sb) { } 
    template <typename T> SomeStream &operator <<(const T &val) 
    { 
    std::ostream::operator<<(val); //Trouble in there! 
    std::cout << "<<" << " " << typeid(T).name() << " " << val << std::endl; 
    /*some other behavior*/ 
    return *this; 
    } 
    SomeStream &operator <<(ostream& (*val) (ostream&)) 
    { 
    std::ostream::operator<<(val); 
    /*some other behavior*/ 
    return *this; 
    } 
    SomeStream &operator <<(ios_base& (*val) (ios_base&)) 
    { 
    std::ostream::operator<<(val); 
    /*some other behavior*/ 
    return *this; 
    } 
}; 

當我打電話給家長操作員std::ostream::operator<<(val); val cast到void*而不是正常工作。 如何正確做?以及爲什麼直接致電operator<<ostream與間接呼叫不一樣。

+0

輸出'運營商<<()'是一個全球性的模板函數不'的std :: ostream'的成員。 –

+0

'(cout.operator <<)(「11122333」);'? – 2016-01-13 12:36:07

+1

@Kilanny - 它實際上是'std :: operator <<(cout,「11122333」);'。 –

回答

3

輸出operator <<對於const char*不是ostream類型的成員。 Only those重載是成員函數,其中之一是void*。 也有non-member overloads

有解決方法:

template <typename T> SomeStream &operator <<(const T &val) 
    { 
    static_cast<std::ostream&>(*this) << val; //Trouble in there! 
    std::cout << "<<" << " " << typeid(T).name() << " " << val << std::endl; 
    /*some other behavior*/ 
    return *this; 
    } 
+0

只有'static_cast (* this)<< val;' ->工作。 'static_cast (* this)<< val;' ->不工作 - >錯誤C2248:'std :: basic_ostream <_Elem,_Traits> :: basic_ostream':無法訪問類 – Jesus05

+0

@ Jesus05中聲明的私有成員當然,對不起,只是印刷錯誤。 – ForEveR

+0

非常感謝您的決定。我很高興:) – Jesus05