2011-02-07 125 views
2

地獄!我正在嘗試創建一個能夠幫助我將文本輸出到stdout的類......無論如何,除了一件事之外,一切都在起作用。假設我已經創建了我的類的對象。當我這樣做,一切正常prefectly:爲QString繼承std :: ostream和operator <<的類

out<<"test test"<<std::endl; 

而且還當我做這個工作:

out<<QString("another string")<<std::endl; 

但是,當我試圖鏈,這兩個東西在一起,像這樣:

out<<"test test"<<std::endl<<QString("another string")<<std::endl; 

我得到那個超大錯誤,最終告訴我,運算符< <不接受QString類型的參數。這是奇怪的,因爲它的工作原理確定,當我不連鎖的QString ......還有這個作品:

out<<"test test"<<std::endl<<"another string"<<std::endl; 

這:

out<<QString("another string")<<std::endl<<"test test"<<std::endl; 

所以我想我有問題,我的操作< <功能...要麼我沒有正確地使運營商< <,要麼我沒有返回正確的價值。或者也許別的東西是錯的。無論如何,我無法弄清楚,所以你能幫我嗎?貝婁源代碼:

output.h:http://xx77abs.pastebin.com/b9tVV0AV output.cpp:http://xx77abs.pastebin.com/5QwtZRXc

當然,超級大錯誤:d

http://xx77abs.pastebin.com/8mAGWn47

編輯:所有你想知道,我沒有使用命名空間...

+0

你從哪裏測試這些打印輸出? `output.cpp`? – 2011-02-07 14:57:52

回答

1

這編譯爲我(與你的第三個鏈接命令行):

#include <iostream> 
#include <sstream> 
#include <QString> 

class Output: public std::ostream 
{ 
    friend std::ostream& operator<<(std::ostream &out, const QString var); 
private: 

    class StreamBuffer: public std::stringbuf 
    { 
    private: 
     std::ostream &out; 
     QString prefix; 

    public: 
     StreamBuffer(std::ostream& str, const QString &p); 
     virtual int sync(); 
    }; 

    StreamBuffer buffer; 

public: 
    Output(const QString &prefix); 
}; 
Output::Output(const QString &prefix) : 
    std::ostream(&buffer), buffer(std::cout, prefix) 
{ 

} 

Output::StreamBuffer::StreamBuffer(std::ostream& str, const QString &p) 
    :out(str) 
{ 
    prefix = p + "-> "; 
} 

std::ostream& operator<<(std::ostream &out, const QString var) 
{ 
    out<<qPrintable(var); 

    return out; 
} 

int Output::StreamBuffer::sync() 
{ 
    out <<qPrintable(prefix)<< str(); 
    str(""); 
    out.flush(); 
    return 0; 
} 

int main() 
    { 
    Output out (QString (">")) ; 
    out<<"test test"<<std::endl; 
    out<<QString("another string")<<std::endl; 
    out<<"test test"<<std::endl<<QString("another string")<<std::endl; 
    } 

如果它編譯於你,你應該能夠把它演變成發生故障的代碼,以找到錯誤。

+0

感謝你的觀點=)我試着編譯你的代碼,它的工作。然後我把它放在單獨的文件中,它不起作用。然後我嘗試了幾件事,發現解決方案是將operator <<定義從.cpp移到.h文件。之後,我得到了一些有關多個定義的錯誤,我通過聲明operator << as inline function :)來解決這個問題:)感謝您的幫助! – xx77aBs 2011-02-07 19:19:07

+1

啊,是的,現在很明顯! `std :: ostream&operator <<(std :: ostream&out,const QString var)`不在頭文件中聲明。另一種解決方案是頭文件中的`extern std :: ostream&operator <<(std :: ostream&out,const QString var);`。 – TonyK 2011-02-07 19:58:05

1

你在使用命名空間嗎?如果是的話,你是否在特定的命名空間中爲QString定義了operator<<?我不能看到上面的代碼有任何問題(除了超載應該接受一個const引用而不是一個副本!)

編輯:應該添加,如果它是在一個命名空間,將其移出,否則它不會被發現。

EDIT2:在你的類聲明之後,將operator<<的聲明添加到頭文件中 - 編譯器在你做之前不知道這個超載的存在。

std::ostream& operator<<(std::ostream &out, const QString& var); 
+0

我沒有使用名稱空間...是的,我忘了輸入&;)我會解決這個問題,謝謝 – xx77aBs 2011-02-07 15:17:47

1

我覺得不得不指出,Qt提供了一個功能/類來完成這個,它被稱爲QDebug。既然你已經綁定了Qt,使用它不應該是一個問題。

相關問題