在写一个hufftree,其中 HuffTree 的结点 Root 的类型是 HuffNode, 而 HuffNode 有两个子类 LeafNode 和 IntlNode ,huffTree 是由这两种类型的指针结点组成。问题是我在调用 Root 显示的是 HuffNode 类型(父类)的,而不是 LeafNode* 或 IntlNode*类型的,调用子类的函数报错显示成员函数未定义。
template <typename E> class HuffNode {
public:
virtual ~HuffNode() {}
virtual int weight() = 0;
virtual bool isLeaf() = 0;
};
template <typename E>
class LeafNode : public HuffNode<E> {
private:
E it;
int wgt;
public:
LeafNode(const E& val, int freq)
{ it = val; wgt = freq; }
int weight() { return wgt; }
E val() { return it; }
bool isLeaf() { return true; }
};
template <typename E>
class IntlNode : public HuffNode<E>{
private:
HuffNode<E>* lc;
HuffNode<E>* rc;
int wgt;
public:
IntlNode(HuffNode<E>* l, HuffNode<E>* r)
{ wgt = l->weight() + r->weight(); lc = l; rc = r; }
int weight() { return wgt; }
bool isLeaf() { return false; }
HuffNode<E>* left() const { return lc; }
void setLeft(HuffNode<E>* b)
{ lc = (HuffNode<E>*)b; }
HuffNode<E>* right() const { return rc; }
void setRight(HuffNode<E>* b)
{ rc = (HuffNode<E>*)b; }
};
template <typename E>
class HuffTree {
private:
HuffNode<E>* Root;
public:
HuffTree(E& val, int freq)
{ Root = new LeafNode<E>(val,freq); }
HuffTree (HuffTree<E>* l, HuffTree<E>* r)
{ Root = new IntlNode<E>(l->root(), r->root()); }
~HuffTree(){}
HuffNode<E>* root() { return Root; }
int weight() { return Root->weight(); }
};