2011-08-13 67 views
1

Possible Duplicates:
Why copying stringstream is not allowed?
how copy from one stringstream object to another in C++?問題的ostringstream和拷貝構造

編譯T級失敗,Visual C++和GCC產生輸入輸出流模板錯誤。下面是代碼:

#include <sstream> 

class T 
{ 
    static T copy; 

    std::ostringstream log; 

    T()   {} 
    T(const T& t) {log = t.log;} 
    ~T()   {copy = *this;} 
}; 

T T::copy; 

更改日誌數據成員類型爲字符串,使得它編譯並運行正常。這是一種合法行爲嗎?

回答

3

C++中的任何流類的複製構造函數和複製賦值已被製作private。這意味着,你不能讓std::ostringstream對象的副本:

std::ostringstream ss; 

std::ostringstream ss1(ss); //not allowed - copy-constructor is private 
ss1=ss; //not allowed - copy-assignment is private 
+0

OK,這是真的,但我得到了同樣的錯誤,即使空的拷貝構造函數:'T(const的T&T){}' –

+0

@保羅:郵政實際的代碼和錯誤。 – Nawaz

+0

@Nawasz:代碼是在我的問題上面的複製構造函數替換爲:'T(const T&t){}'或'T(const T&t){log << t.log.str();}'或'T(const T&t){log << t.log.rdbuf();}'。我總是得到:_'std :: basic_ios <_Elem,_Traits> :: operator =':沒有虛擬基地聲明的私人成員的可訪問路徑'std :: basic_ios <_Elem,_Traits>'_ –

1

我認爲ostringstream沒有重載賦值(=)運算符。

3

std::ostringstream是不可拷貝,這就是爲什麼你得到錯誤。有關更多詳細信息,請參見this answer,以瞭解如何解決此問題。

T(const T& t) {log << t.log.rdbuf(); } 
+0

它仍然會產生相同的錯誤:'std :: basic_ios <_Elem,_Traits> :: operator =':在虛擬基地中聲明的私有成員沒有可訪問路徑'std :: basic_ios <_Elem,_Traits>' –