我有一个函数,我要为其传递一个变量;但是,该变量是一个模板变量。我不知道我应该如何使用模板参数创建函数的细节。我什至不知道我问的问题是否正确,但是当我编译程序时,main.cpp
文件中出现以下错误:
line 17 error: no matching function for call to 'BSTree<int>::BSTinsert(TNode<int>&)'
line 49 error note: candidates are: void BSTree<T>::BSTinsert(const T&) [with T = int]
我认为我做的一切都是正确的,但这是阻碍我继续前进的一个错误。欢迎和感谢任何和所有帮助!(我不认为需要显示其他两个文件 -treeNode.h
和treeNode.cpp
- ,但我以前错了。如果是,请让我知道,我很乐意发布它们。再次感谢您!
主.cpp:
#include <iostream>
#include <string>
#include "BSTree.cpp"
using namespace std;
int main()
{
BSTree<int> bt;
TNode<int> item;
for(int i=0; i<13; i++)
{
cout << "Enter value of item: ";
cin >> item;
bt.BSTinsert(item); //this is the line with the error
}
cout << "Hello world!" << endl;
return 0;
}
BSTree.h:
#ifndef BSTREE_H_INCLUDED
#define BSTREE_H_INCLUDED
#include "treeNode.cpp"
template <typename T>
class BSTree
{
TNode<T> *root;
void insert(TNode<T> * & r, const T & item);
public:
BSTree();
TNode<T>* getRoot();
void BSTinsert(const T & item);
};
#endif // BSTREE_H_INCLUDED
BSTree.cpp:
#include <iostream>
#include <string>
#include "BSTree.h"
template <typename T>
void BSTree<T>::insert(TNode<T> * & r, const T & item)
{
if(r == NULL)
TNode<T> newNode = new TNode<T>(item);
else if(r == item)
return;
else if(r->nodeValue > item)
insert(r->leftChild, item);
else if(r->nodeValue > item && r->leftChild == NULL)
{
TNode<T> newNode = new TNode<T>(item);
r->leftChild = newNode;
newNode->parent = r;
}
else if(r->nodeValue < item)
insert(r->rightChild, item);
else if(r->nodeValue < item && r->rightChild == NULL)
{
TNode<T> newNode = new TNode<T>(item);
r->rightChild = newNode;
newNode->parent = r;
}
}
template <typename T>
BSTree<T>::BSTree()
{
root = NULL;
}
template <typename T>
TNode<T>* BSTree<T>::getRoot()
{
return root;
}
template <typename T>
void BSTree<T>::BSTinsert(const T& item) //this is the line the note is referring to
{
TNode<T> tempRoot = getRoot();
insert(tempRoot, item);
}
树节点.cpp:
#include <string>
#include <iostream>
#include "treeNode.h"
using namespace std;
template <typename T>
TNode<T>::TNode()
{
parent = NULL;
leftChild = NULL;
rightChild = NULL;
nodeValue = 0;
}
template <typename T>
TNode<T>::TNode(const T&item, TNode<T> *left, TNode<T> *right, TNode<T> *par)
{
parent = par;
leftChild = left;
rightChild = right;
nodeValue = item;
}
template <typename T>
void TNode<T>::printNodeInfo()
{
cout << "Value: " << nodeValue << endl;
if(parent != NULL)
cout << "Parent Value: " << parent << endl;
if(leftChild != NULL)
cout << "Left Child Value: " << leftChild << endl;
if(rightChild != NULL)
cout << "Right Child Value: " << rightChild << endl;
}
树节点.h:
#ifndef TREENODE_H_INCLUDED
#define TREENODE_H_INCLUDED
template <typename T>
class TNode
{
public:
T nodeValue;
TNode<T> *leftChild, *rightChild, *parent;
TNode();
TNode(const T&item, TNode<T> *left = NULL, TNode<T> *right = NULL, TNode<T> *par = NULL);
void printNodeInfo();
friend std::istream& operator>>( std::istream& i, TNode<T>& item ){return i;}
};
#endif // TREENODE_H_INCLUDED