2011-04-11 37 views
0

我有一個程序,應該效仿簡單的文件系統,我想打印目錄的結構,所以我重載<<運營商,並呼籲通過我的結構rectursion去另一個函數。它可以工作,但是在輸出中的一些行之前有一些奇怪的十六進制值。我在ostream上操作的方式有什麼問題嗎? (我沒有包括班級的定義,但它不重要)奇怪的字符出現在ostream的在C++

謝謝大家,對於任何答案!

std::ostream& printTree(std::ostream& os, const CFileSystem::TDir* x, int nmbTabs) 
{ 
    int k; 
    const CFileSystem::TDir * nxt = x; 
    //cout << pocetTabu<<endl; 
    while(nxt){ 
     os<<"--"; 
     for(k=0;k<nmbTabs;k++){ 
      os << '\t' ; 
     } 
     os<<"--"; 
     os << nxt->m_Name << endl; 
     if(nxt->m_Sub){ 
      os << printTree(os,nxt->m_Sub,nmbTabs+1); 
     } 
     nxt=nxt->m_Next; 
    } 
    return os; 
} 
std::ostream& operator <<(std::ostream& os, const CFileSystem& x) 
{ 
    os << "/" << endl; 
    os << printTree(os, x.m_Root,1); 
    return (os); 
} 

回答

5
os << printTree(os, x.m_Root,1); 

這是什麼? printTree返回std::ostream &,並且您正試圖輸出該(ostream)?

這應該是這樣的:

printTree(os, x.m_Root,1); 

這意味着,你的operator<<應該被實現爲:

std::ostream& operator<<(std::ostream & os, const CFileSystem & x) 
{ 
    os << "/" << std::endl; 
    return printTree(os, x.m_Root,1); 
} 
+1

+1良好的漁獲物。輸出ostream對象本身。 – 2011-04-11 14:31:18

+1

噢,我的..所以十六進制值實際上是對ostream的在內存中不會忽略的,有趣的。非常感謝! – Randalfien 2011-04-11 14:37:44