【问题标题】:Trying to create new instance of class using template, unexpected error尝试使用模板创建类的新实例,出现意外错误
【发布时间】:2012-06-16 05:19:15
【问题描述】:

尝试使用模板制作B inary S搜索T ree(简称BST)。

当我尝试创建 BST 的新实例时,我收到了一个意外错误。我希望解决方案不涉及指针,因为我希望将它们保持在最低限度。

现在我有:

template <typename Type>
class BST {                 // The binary search tree containing nodes
private:
    BSTNode<Type> *root;    // Has reference to root node

public:
    BST ();
    bool add (int, Type);
};

以及节点类型:

编辑:当我剪下代码以取消阻碍文本时,我忘记了构造函数,现在它被添加了

template <typename Type>
class BSTNode {    // Binary Search Tree nodes
private:
    int key;       // we search by key, no matter what type of data we have
    Type data;
    BSTNode *left;
    BSTNode *right;

public:
    BSTNode (int, Type&); 
    bool add (int, Type);
};

EDIT2:这是实际的构造函数

template <typename Type>
BSTNode<Type>::BSTNode (int initKey, Type &initData) {
     this->key = initKey;
     this->data = initData;
     this->left = NULL;
     this->right = NULL;
}

我想尝试测试是否有任何工作/不工作

BSTNode<int> data = new BSTNode (key, 10);

我得到:BSTNode 之前的预期类型说明符。我不知道我做错了什么,但我希望有一件事是我不必使用数据作为指针。

BSTNode<int> data = new BSTNode<int> (key, 10);

也不起作用,似乎它认为&lt; int &gt;&lt; &amp; int&gt; 并且不匹配

【问题讨论】:

    标签: c++ templates pointers binary-search-tree


    【解决方案1】:

    首先,您需要在赋值的 RHS 上完全指定类型,并且由于您正在使用 new 实例化一个动态分配的节点,因此 LHS 应该是一个指针:

    BSTNode<int>* data = new BSTNode<int> (key, 10);
                ^                     ^
    

    如果不需要节点指针,则使用

    BSTNode<int> data(key, 10);
    

    其次,您的 BSTNode&lt;T&gt; 类没有采用 int 和 Type 的构造函数,因此您也需要提供它。

    template <typename Type>
    class BSTNode {
     public:
      BSTNode(int k, const Type& val) : key(k), data(val), left(0), right(0) { .... }
    };
    

    【讨论】:

    • 忘记粘贴了,现在就在这里,是不是哪里错了?
    • @Kalec 构造函数是可以的,但是最好使用初始化列表来避免不必要的默认初始化/赋值。
    • @Kalec 你可能不想在构造函数中通过值传递Type
    • 好的,但我仍然有同样的问题,因为构造函数已经存在,所以它没有任何改变。我不知道为什么会出现编译错误。
    • @Kalec 因为我在答案顶部给出的原因?
    猜你喜欢
    • 1970-01-01
    • 2015-02-20
    • 2021-04-10
    • 2016-10-04
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多