繁体   English   中英

带结构的模板

[英]Template with struct

我正在设计一个二进制搜索树,它允许用户输入任何数据类型的值,而不仅仅是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'的模板声明
我如何使用带有struct变量的模板?

您无法在模板类声明后声明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>*);
};
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>; 

    // […]
};

您可以使用typedef定义您的Node类型:

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM