2014-06-11 118 views
3

我有以下代碼C++的operator <<(無效*)

#include <iostream> 
#include <sstream> 

class oTraceStream : public std::ostringstream 
{ 
public : 

    oTraceStream(const int from, const unsigned int level) 
    : m_from(from) 
    , m_level(level) 
    { 
    } 

    virtual ~oTraceStream(void) 
    { 
     std::cout << str(); 
    } 

private : 
    // unused for this sample 
    int m_from; 
    unsigned int m_level; 
}; 


int main(int argc, char* argv[]) 
{ 
    oTraceStream(0,0) << "1st part " << " 2nd part" << std::endl; 
    { 
     oTraceStream tmp(0,0); 
     tmp << "1st part " << " 2nd part" << std::endl; 
    } 

    return 0; 
} 

隨着MS的視覺6.0或舊的gcc(2.X)時,2個輸出是相同的。

1st part 2nd part 
1st part 2nd part 

隨着微軟的Visual 2008年或最近的海灣合作委員會(4.x)時,第一行的第一個字符串顯示爲指針

0x80493ec 2nd part 
1st part 2nd part 

有人能解釋我爲什麼,最近蒙山編譯第一線使用ostream :: operator < <(const void * p)而不是ostream :: operator < <(const char *)顯示?

+0

什麼是'str'? –

+2

@LuchianGrigore標準'std :: ostringstream :: str()' – Erbureth

+2

備註:流類如'ostringstream'不應被分類。只有'streambuf'應該。 (好吧,你可以創建類似的子類,因爲ostringstream對應於'stringbuf'。) – Potatoswatter

回答

4

void const *過載是std::ostream的成員,而char const *超載是非成員。臨時oTraceStream(0,0)對象不會綁定到非成員operator <<使用的非常量引用,但它將綁定到成員使用的隱式this參數。

C++ 11導致行爲回到您的期望,因爲它增加了一個operator <<,它取一個右值(例如一個臨時對象子表達式)並將其切換爲一個左值(例如,一個命名對象子表達式)。