c++ - 尝试使用模板创建类的新实例,出现意外错误

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

尝试使用模板制作B二元S搜索T树(简称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);

也不行,好像信了< int >< & int>而且不匹配

最佳答案

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

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

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

BSTNode<int> data(key, 10);

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

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

关于c++ - 尝试使用模板创建类的新实例,出现意外错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59725453/

相关文章:

c++ - 使用 lambda 参数数组

c++ - 编译器错误 : cannot convert from object_type<T> to object_type<T> in c++

swift - 如何在 Swift 的 NSNetService 上使用 getInputStream()?

c++ - 升压:Serialization: Who cleans up the deserialized data?

c++ - Sleep() 与 _sleep() 函数

c++ - 如何让Widget的位置固定?

c++ - 我需要写一个程序

C++ template double std::complex<double> 范数和积

python - SWIG 3 使用模板化构造函数包装未模板化的类

c++ - 如何使用指针从不同的函数访问局部变量?