我会尝试保持代码简短。
我正在尝试使用模板制作一个 B inary S earch T ree(简称BST)。
在我的添加功能中,我收到错误,我确定我在某种程度上滥用模板
由于模板,所有这些代码都在.h(标题)文件中。
编辑: const类型&错误是因为我摆弄,它实际上不是我编译的代码,而是从前一个关于堆栈溢出的问题
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); // key, data
bool add (int, Type);
};
添加功能:
template <typename Type>
bool BSTNode<Type>::add(int newKey, Type newData) {
if (newKey < this->key) {
if (left == NULL) {
this->left = new BSTNode<Type>(int newKey, Type newData);
}
} else {
this->right = new BSTNode<Type>(int newKey, Type newData);
}
return false;
}
这是我收到错误的地方:
this->left = new BSTNode<Type>(int newKey, Type newData);
int之前的预期主表达式
答案 0 :(得分:2)
您没有特别误导模板,但是您滥用参数!
this->left = new BSTNode<Type>(int newKey, Type newData);
看起来应该更像
this->left = new BSTNode<Type>(newKey, newData);
答案 1 :(得分:1)
它应该是this->left = new BSTNode<Type>(newKey, newData);
,没有任何类型。
答案 2 :(得分:1)
错误很明显:
bool add (int, Type);
VS
bool add(int newKey, const Type &newData)
您应该将类定义中的声明更改为:
bool add (int, const Type&);
并从语句中删除类型:
this->right = new BSTNode<Type>(int newKey, Type newData);
this->right = new BSTNode<Type>(int newKey, Type newData);
应该是
this->right = new BSTNode<Type>(newKey, newData);
this->right = new BSTNode<Type>(newKey, newData);