C++ 尝试使用模板创建新的类实例,意外错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11011676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to create new instance of class using template, unexpected error
提问by Kalec
Trying to make a Binary Search Tree (BST for short) using a template.
试图使乙inary小号操作搜索Ť使用模板REE(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.
当我尝试创建 BST 的新实例时,出现意外错误。我希望解决方案不涉及指针,因为我希望将它们保持在最低限度。
For now I have:
现在我有:
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);
};
And the Node type:
和节点类型:
EDIT: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);
};
EDIT2:Here is the actual constructor
EDIT2:这是实际的构造函数
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);
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 之前的预期类型说明符。我不知道我做错了什么,但我希望的一件事是我不必使用数据作为指针。
BSTNode<int> data = new BSTNode<int> (key, 10);
Also does not work, seems it believes < int >
is < & int>
and it doesn't match
也不起作用,似乎它认为< int >
是< & int>
和不匹配
回答by juanchopanza
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:
首先,您需要在赋值的 RHS 上完全指定类型,并且,由于您正在使用 实例化动态分配的节点new
,因此 LHS 应该是一个指针:
BSTNode<int>* data = new BSTNode<int> (key, 10);
^ ^
If you don't need a node pointer, then use
如果您不需要节点指针,则使用
BSTNode<int> data(key, 10);
Second, your BSTNode<T>
class doesn't have a constructor taking an int and a Type
, so you need to provide that too.
其次,您的BSTNode<T>
类没有采用 int 和 a 的构造函数Type
,因此您也需要提供它。
template <typename Type>
class BSTNode {
public:
BSTNode(int k, const Type& val) : key(k), data(val), left(0), right(0) { .... }
};