可能重复:
为什么模板只能在头文件中实现?
我以前碰到过这堵墙,但我不知道如何修复它。在 g++ 中,每当我尝试创建 BinaryTree 类的对象时,都会出现此错误:
/home/bej0843/cs261/Assignment1/main.cpp:9: undefined reference to `BinaryTree<char>::BinaryTree()'
这是头文件的代码:
#ifndef BINARYTREE_H
#define BINARYTREE_H
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
template<typename Type>
class BinaryTree
{
public:
struct TreeNode
{
Type nodeinfo;
BinaryTree<Type> *left;
BinaryTree<Type> *right;
};
BinaryTree();
void setInfo(Type a);
void setSubtree(Type a);
bool isEmpty();
Type Info();
void inOrder();
void preOrder();
void postOrder();
virtual ~BinaryTree();
protected:
TreeNode *root;
stack<TreeNode*> s;
stack<TreeNode*> temp;
private:
void postOrder(TreeNode *r);
};
#endif /* BINARYTREE_H */
这是它的实现代码:
#include "BinaryTree.h"
template <typename Type>
BinaryTree<Type>::BinaryTree(){
root = NULL;
}
template <typename Type>
void BinaryTree<Type>::setInfo(Type a){
root->nodeinfo = a;
root->left = NULL;
root->right = NULL;
s.push(root);
}
template <typename Type>
void BinaryTree<Type>::setSubtree(Type a){
root->nodeinfo = a;
root->left->root = s.top();
s.pop();
root->right->root = s.top();
s.pop();
s.push(root);
}
template <typename Type>
bool BinaryTree<Type>::isEmpty(){
return (root==NULL);
}
template <typename Type>
Type BinaryTree<Type>::Info(){
return root->nodeinfo;
}
template <typename Type>
void BinaryTree<Type>::inOrder(){
TreeNode *c;
c = s.top();
while (c!=NULL || (!temp.empty())){
if (c!=NULL)
{
temp.push(c);
c = c->left;
}
else{
c = temp.top();
temp.pop();
cout << c->nodeinfo +" ";
c = c->right;
}
}
}
template <typename Type>
void BinaryTree<Type>::postOrder(){
postOrder(s.top());
}
template <typename Type>
void BinaryTree<Type>::postOrder(TreeNode *r){
temp.push(s.top());
TreeNode *c = temp.top();
s.pop();
postOrder(c->left->root);
postOrder(c->right->root);
cout << c->nodeinfo + " ";
}
template <typename Type>
void BinaryTree<Type>::preOrder(){
TreeNode*c = s.top();
while (c!=NULL||(!temp.empty())){
if (c!=NULL){
cout << c->nodeinfo + " ";
temp.push(c);
c=c->left;
}
else{
c=temp.top();
temp.pop();
c=c->right;
}
}
}
template <typename Type>
BinaryTree<Type>::~BinaryTree(){
}
我主要打电话给:
BinaryTree<char> tree;
并得到错误。帮助?