2014-10-27 96 views
1

我正在設計一個二進制搜索樹,它允許用戶輸入任何數據類型的值,而不僅僅是int
爲了實現這一點,我試圖使用模板與結構。 我定義我的結構如下模板與結構

template <class T> 
struct node 
{ 
    struct node *left; 
    T info; 
    struct node *right; 
}*root; 

我現在想在一類稱爲BST使用本(二叉搜索樹)

template <class T> 
class bst 
{ 
    public: 
    void insert(node *,node *); 
    void inorder(node *); 
}; 

但是編譯器引發錯誤, 模板聲明'node < T> * root'
我怎樣才能使用模板結構變量?

回答

2

你不能聲明root模板類聲明之後,因爲模板參數不能被推斷,你可以:

template <class T> 
struct node 
{ 
    struct node *left; 
    T info; 
    struct node *right; 
}; 

node <int> * root; 

您應該在使用node時指定模板參數類型,如:

template <class T> 
class bst 
{ 
    public: 
    void insert(node<T>*, node<T>*); 
    void inorder(node<T>*); 
}; 
+0

thnaks ..幫了我很多。 – Pradeep 2014-10-27 10:32:14

0

您可以使用typedef定義了自己的節點類型:

#include <iostream> 
#include <typeinfo> 

using namespace std; 

template <class T> 
struct node 
{ 
    node *left; 
    T info; 
    node *right; 

    typedef node<T>* root; 
}; 

int main() 
{ 
    node<int>::root root = new node<int>(); 
    cout<<typeid(root).name()<<endl; 

    return 0; 
} 
+0

它顯示以下錯誤。 ** T不命名一個類型** – Pradeep 2014-10-27 09:34:34

+0

這並不回答這個問題。 – Columbo 2014-10-27 09:35:31

+0

@Pradeep我以前的答案是錯誤的,因爲我誤解了這個問題,現在檢查。 – Nik 2014-10-27 09:53:33

1
template <class T> 
struct node 
{ 
    // […] 
} *root; 

你不能沒有類型聲明的對象。 node是一個模板,而不是一個類型 - 哪種類型應root有?
我相信你想聲明它裏面bst

template <class T> 
class bst 
{ 
    node<T>* root; 
    // ^^^ 
    // Supply the appropriate template arguments 

    // ... or use a typedef: 
    using node_type = node<T>; 

    // […] 
};