2014-10-27 80 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>; 

    // […] 
};