在寫一個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(); }
};
你子類對應的函數也要是virtual虛函數