【问题标题】:Template with struct带有结构的模板
【发布时间】:2014-12-22 10:49:59
【问题描述】:

我正在设计一个二叉搜索树,它允许用户输入任何数据类型的值,而不仅仅是 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* root'的模板声明
如何将模板与结构变量一起使用?

【问题讨论】:

    标签: c++ class templates struct binary-search-tree


    【解决方案1】:

    你不能在模板类声明之后声明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>*);
    };
    

    【讨论】:

      【解决方案2】:

      您可以使用 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;
      }
      

      【讨论】:

      • 它显示以下错误。 T 没有命名类型
      • 这不能回答问题。
      • @Pradeep 我之前的回答是错误的,因为我误解了这个问题,现在检查一下。
      【解决方案3】:
      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>; 
      
          // […]
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-22
        相关资源
        最近更新 更多