2010-12-07 57 views
0

我想在模板BSTree.h中創建兩個重載操作符,並且遇到了錯誤,它們確實不會告訴我問題是什麼。單獨或聯合運行錯誤代碼的搜索沒有爲我帶來任何東西。無法聲明2個朋友重載<<在模板中.h

第一個重載< <爲BSTree不會導致編譯任何錯誤,但第二次超載< <我爲我的節點結構建立保持返回以下錯誤:

錯誤C4430:缺少類型說明符 - 假設爲int。注意:C++不支持默認int
錯誤C2143:語法錯誤:缺少「」前‘*’

#ifndef BSTREE_H 
#define BSTREE_H 

#include <iostream> 
#include <fstream> 

template <typename T> 
class BSTree{ 

friend ostream& operator<<(ostream&, const BSTree<T>&); 

public: 
    BSTree(); 
    //BSTree(const BSTree &); 
    ~BSTree(); 

    void buildTree(ifstream&); 
    void setType(char); 
    bool getType(char); 

    bool insert(T*); 

    bool isEmpty(); 


private: 
    char type; 

    struct Node{ 
     T* data; 

     //subnode[0] == left subtree 
     //subnode[1] == right subtree 
     Node* subnode[2]; 
    }; 

    Node* head; 
    void destructorHelper(Node* &); 
    bool insertHelper(T*, Node* &); 
    friend ostream& operator<<(ostream&, const Node*&); 

}; 

編譯器說,發生在這裏的節點超載< <代碼行中的錯誤。

template <typename T> 
ostream& operator<<(ostream &output, const BSTree<T> &out) { 
    if(head != NULL) 
     output << head; 
    return output; 
} 

template <typename T> 
ostream& operator<<(ostream &output, const Node* &out) { 
    if(out != NULL){ 
     output << out->subnode[0]; 
     output << *out->data; 
     output << out->subnode[1]; 
    } 

    return output; 
} 

不允許我宣佈2重載< <在同.H即使它們是不同的對象?或者我在我的代碼中搞了些什麼?

回答

2

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

通常這意味着,編譯器不知道的標識作爲一種類型,如此這般假設它是一個參數的名字,用類型隱含爲int。 (在舊的C存在,在一個參數類型的int可以省略的規則。)這樣的代碼

void foo(bar); 

可能會發出此,如果編譯器不知道類型bar並假定void foo(int bar)

template <typename T> 
std::ostream& operator<<(std::ostream &output, const typename BSTree<T>::Node* &out) 
{ 
    // ... 
} 

應該編譯。 (請注意資格std::BSTree::。)

+0

這部分的工作,這樣做只是常量BSTree ::節點*返回C4346錯誤。我不得不做const const typename :: BSTree ::節點*出來讓錯誤消失 – Moniker 2010-12-07 19:28:08

0

也許你需要這個:

常量BSTree ::節點* &出

節點是內部結構。

0

我懷疑問題是ostream不在您的operator<<()朋友函數聲明時的範圍內。

要麼添加using std::ostream;只是內部class BSTree{,或指定完全限定typenames:

friend std::ostream& operator<<(std::ostream&, const BSTree<T>&); 
... 
friend std::ostream& operator<<(std::ostream&, const Node*&); 

無論哪種方式,這些功能的實際定義將需要類似的改變。無論你做什麼,都不要在文件範圍的頭文件中試圖使用using std::ostream;或(更糟糕的)using namespace std;,因爲它會影響翻譯單元中的每個後續聲明。

1

你必須在你的代碼的幾個誤區:

  • 你需要添加<>後聲明成爲朋友
  • 即使你的朋友一個函數體是函數名,你需要指定你調用方法的對象。請記住,函數不會綁定到實例。在過去的原型
  • ,節點不可到達它定義的類之外,你必須精確BSTree ::節點