尝试使用模板创建类的新实例

尝试使用模板创建类的新实例

本文介绍了尝试使用模板创建类的新实例,发生意外错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用模板制作 B 初级 S 检索 T ree(简称BST).

Trying to make a B inary S earch T ree (BST for short) using a template.

当我尝试创建BST的新实例时,出现意外错误.我希望该解决方案不涉及指针,因为我希望将其保持在最低限度.

When I try to create a new instance of my BST I get an unexpected error. I hope the solution does not involve pointers since I would like to keep them at a minimum.

现在我有:

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

节点类型:

编辑:当我将代码切成无障碍的文本时,我忘记了构造函数,现在已经添加了它

When I cut out code to un-encumber text, I forgot the constructor, now it's been added

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

这是实际的构造函数

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

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

I want to try and test if anything works / doesn't work

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

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

And I get: Expected type specifier before BSTNode. I have no idea what I'm doing wrong, but one thing I do hope is I don't have to use data as a pointer.

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

似乎也不相信<int> <&int> 并且不匹配

Also does not work, seems it believes < int > is < & int> and it doesn't match

推荐答案

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

First, you need to fully specify the type on the RHS of the assignment, and, since you are instantiating a dynamically allocated node with new, the LHS should be a pointer:

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

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

If you don't need a node pointer, then use

BSTNode<int> data(key, 10);

第二,您的 BSTNode< T> 类没有带有int和 Type 的构造函数,因此您也需要提供它.

Second, your BSTNode<T> class doesn't have a constructor taking an int and a Type, so you need to provide that too.

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

这篇关于尝试使用模板创建类的新实例,发生意外错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 11:56