2012-08-15 27 views
3

我想做一個自定義cout類,輸出文本到控制檯輸出和日誌文件,當我嘗試運行此代碼的版本不處理鏈接(出< <「one」< < 「two」)它工作正常,但是當我嘗試使它處理鏈接時,它給了我「這個操作符函數的參數太多」。我錯過了什麼?錯誤,同時使自定義cout

class CustomOut 
{ 
    ofstream of; 

public: 
    CustomOut() 
    { 
    of.open("d:\\NIDSLog.txt", ios::ate | ios::app); 
    } 

    ~CustomOut() 
    { 
    of.close(); 
    } 

    CustomOut operator<<(CustomOut& me, string msg) 
    { 
    of<<msg; 
    cout<<msg; 

    return this; 
}}; 
+2

這甚至不會編譯,在'CustomOut'中返回類型''return this'時指針級別不匹配。 – 2012-08-15 17:52:35

回答

5

你需要一個成員operator<<返回的對象實例的引用:

​​

這將讓你「流」到您的CustomOut類的鏈接方式:

CustomOut out; 
out << str_0 << str_i << ... << str_n; 
+0

它工作!謝謝 – Yohannes 2012-08-15 19:08:18

+0

@ user1470033:你有沒有想過接受解決問題的答案? – Grizzly 2012-08-20 23:34:30

+0

我歡迎您提供任何建議 – Yohannes 2012-08-20 23:38:01