为什么我在尝试模板时遇到视觉工作室C++错误

Why I am getting visual studio C++ errors while trying Template

本文关键字:视觉 遇到 工作室 C++ 错误 为什么      更新时间:2023-10-16

代码编译正确。然后当我尝试运行时出现这些构建错误

Error C2955   'Node': use of class template requires template argument list.
Error C2514   'Node': class has no constructors

我对模板了解不多,所以无论我错在哪里,请纠正我。 所以下面的代码是我的头文件

#pragma once
#include<iostream>
using namespace std;
template<class T>
class Node
{
public:
Node *left, *right, *parent;
T key;
Node(){
left = right = parent = NULL;
}
};
template<class T>
class GenericBst {
Node<T>* root;
bool search(Node<T>* current, int value);//Finds a value is present
public:
GenericBst()
{
root = NULL;
}
void insertNode(int value);//Insertation of node
bool search(int value);
};
template<class T>
inline bool GenericBst<T>::search(Node<T>* current, int value)
{
if (current == NULL)
return false;
while (current != NULL)
{
if (current->key == value)
return true;
else
{
if (value < current->key)
current = current->left;
else
current = current->right;
}
}
}
template<class T>
inline void GenericBst<T>::insertNode(int value)
{       
Node<T>*temp = new Node();
temp->key = value;
Node<T> *current = root, *parent = NULL;
while (current != NULL)
{
//Parent is assigned the current position and current goes to the child
parent = current;
if (value < current->key)
{
current = current->left;
}
else
{
current = current->right;
}
}
//Now we check if parent of current is NULL then currnt node is at root
if (parent == NULL)
{
root = temp;//temp was used to store the insertion value. Now root points to it.
}
else if (value < parent->key)
{
parent->left = temp;
}
else
{
parent->right = temp;
}
temp->parent = parent;
}
template<class T>
inline bool GenericBst<T>::search(int value)
{
return search(root,value);
}

主类有

#include<iostream>
using namespace std;
#include "GenericBst.h"
#include <iostream>
int main()
{
GenericBst<int> Obj;
//GenericBst<string> Obj;
std::cout << "Welcome to generic Worldn";
int i = 1;
int value;
while (i != 0)
{
cout << "nSelect:nt1. Insert a node.t2. Search a Nodent0. Quit" << endl;
switch (i)
{
case 0:
i = 0;
cout << "nttByen";
break;
case 1:
cout << "Enter value: ";
cin >> value;
Obj.insertNode(value);
break;
case 2:
cout << "Enter value: ";
cin >> value;
cout << Obj.search(value);
break;
}
}
}

应在模板类中显式指定模板参数。

Node<T>*temp = new Node();

必须是:

Node<T>*temp = new Node<T>();