读书人

正在学二叉树 请问几个小问题

发布时间: 2012-03-09 21:42:55 作者: rapoo

正在学二叉树 请教几个问题
这是教材上给的声明:

C/C++ code
 
template <class Type> class BinaryTree;
template <class Type> class BinTreeNode
{
friend class BinaryTree <Type>;
public:
BinTreeNode() {leftChild=0;rightChild=0;}
BinTreeNode(Type item,BinTreeNode <Type> *left=0,BinTreeNode <Type> *right=0) {data=item;leftChild=left;rightChild=right;}

Type &GetData() const {return data;}
BinTreeNode *GetLeft() const {return leftChild;}
BinTreeNode *GetRight() const {return rightChild;}

void SetData(const Type &item) {data=item;}
void SetLeft(BinTreeNode <Type> *L) {leftChild=L;}
void SetRight(BinTreeNode <Type> *R) {rightChild=R;}
private:
BinTreeNode <Type> *leftChild,*rightChild;
Type data;
};

template <class Type> class BinaryTree
{
public:
BinaryTree() {root=0;}
BinaryTree(Type value) {RefValue=value;root=0;}
virtual ~Binary() {destroy(root);}

virtual int IsEmpty() {return root==0?1:0;}
virtual BinTreeNode <Type> *Parent(BinTreeNode <Type> *current) {return root==0 || root==current?0:Parent(root,current);}
virtual BinTreeNode <Type> *LeftChild(BinTreeNode <Type> *current) {return root!=0?current->leftChild:0;}
virtual BinTreeNode <Type> *RightChild(BinTreeNode <Type> *current) {return root!=0?current->rightChild:0;}
virtual int Insert(const Type &item);
virtual int Find(const Type &item) const;
const BinTreeNode <Type> *GetRoot() const {return root;}

friend istream &operator>>(istream &,BinTree <Type> &Tree);
friend ostream &operator < <(ostream &,BinTree <Type> &Tree);
private:
BinTreeNode <Type> *root;
Type RefValue;

BinTreeNode <Type> *Parent(BinTreeNode <Type> *start,BinTreeNode <Type> *current);
int Insert(BinTreeNode <Type> * &current,const Type &item);
void Traverse(BinTreeNode <Type> *current,ostream &out) const;
int Find(BinTreeNode <Type> *current,const Type &item) const;
void destroy(BinTreeNode <Type> *current);
};


1.二叉树没有继承类 为什么析构函数是虚函数?
2.Parent() Insert() Find()为什么同时在public和private中声明 而且在public中为虚?

[解决办法]
1.对于1,这样声明的目的是说明此类是用来继承的,如果不用来继承,那就没必要了
2.public声明是给外部调用的,且可能被重载;private的声明,是内部实现pulic的声明用的
[解决办法]
1。析构函数定义成虚函数是为了防止有其他类继承该类的时候,通过基类指针去析构派生类对象时析构不完全,不定义成虚函数,则只会调用基类的析构函数

2。那三对函数是重载函数,public中的函数是提供给外部的接口,praivate中的函数才进行具体的操作,
定义成虚函数也是考虑到有可能这个类会被继承,这样通过基类指针或引用调用函数时,能够表现出多态性

读书人网 >C++

热点推荐