I am writing a binary search tree program and I am getting the error
"Main.cpp:30:20: error: use of undeclared identifier 'T'
BiTreeNode<T> *node = new BiTreeNode<T> (b);.
我已经使用类模板编写了2个其他程序,之前我从未遇到此错误。 任何帮助将不胜感激。提前致谢!我刚刚从Eclipse切换 到NetBeans。我不认为这会导致错误,但我可能错了......
//////Beginning of BiTree.h//////
#ifndef BITREE_H
#define BITREE_H
#include "BiTreeNode.h"
#include <iostream>
using namespace std;
template <class T>
class BiTree
{
private:
BiTreeNode<T> *root;
//use const because when we insert the data of type T from the object,
//we want to only read it and not change it
void insert(const T &d, BiTreeNode<T> *ptr)
{
if(ptr == NULL)
{
//creates a new tree node with data type d and its right and
//left child node pointers NULL
ptr = new BiTreeNode<T>(d, NULL, NULL);
}
else if(d <= ptr -> data)
{
insert(d, ptr -> leftChild);
}
else if(d >= ptr -> data)
{
insert(d, ptr -> rightChild);
}
}
public:
BiTree()
{
root = NULL;
}
//By adding the &, the d copies the data from the object passed as an
//argument for the insert function in main into a new node which is then put into the tree
//Added the const since when we take in the data in from the object passed as an object
//for the insert function in main. We don't want to change the data, we just want to read it
void insert(const T &d)
{
//d is the data type you want to send in
insert(d, root);
}
//prints a tree rooted at ptr in sorted order
void inOrder(BiTreeNode<T> *ptr, ostream & out)
{
if(ptr != NULL)
{
inOrder(ptr -> leftChild, out);
out << ptr -> data << endl;
inOrder(ptr -> rightChild, out);
}
}
void preOrder()
{
cout << "printing out in pre-order" << endl;
}
void postOrder()
{
cout << "printing out in post-order" << endl;
}
void printTree()
{
}
};
#endif /* BITREE_H */
//////End of BiTree.h//////
////// BiTreeNode.h的开头///////
#ifndef BITREENODE_H
#define BITREENODE_H
#include "BiTree.h"
#include <iostream>
using namespace std;
template <class T>
class BiTree;
template <class T>
class BiTreeNode
{
private:
T data;
BiTreeNode<T> *leftChild;
BiTreeNode<T> *rightChild;
public:
BiTreeNode(T Data)
{
data = Data;
leftChild = NULL;
rightChild = NULL;
}
friend class BiTree<T>;
};
#endif /* BITREENODE_H */
////////End of BiTreeNode.h//////
////Start of Main.cpp/////
#include <cstdlib>
#include <iostream>
#include <vector>
#include <ctime>
#include "BiTree.h"
#include "BiTreeNode.h"
using namespace std;
int main()
{
srand(time(NULL));
BiTree<int> tree;
int a = 1 + rand() % 100;
for(int i=0; i<a; i++)
{
int b = 1 + rand() % 100;
BiTreeNode<T> *node = new BiTreeNode<T>(b);
}
tree.postOrder();
tree.preOrder();
return 0;
}
/////End of Main.cpp//////
答案 0 :(得分:0)
您需要在某处定义T.通过包含您的T.h文件或声明实际的类T。
正如我所看到你为T定义了一个int,你必须在行中用int替换T,如下所示:
BiTreeNode<int> *node = new BiTreeNode<int>(b);