1.树结构是一类重要的非线性数据结构。树结构在客观世界中广泛存在,如人类社会的族谱和各种社会组织机构都可以用树形象表示,树在计算机领域中也得到广泛应用,尤以二叉树最为常用。
2. 有以下Tree(树)、Binary_Tree(二叉树)和Binary_Sort_Tree(二叉排序树)类的定义,其中Binary_Tree继承了Tree,Binary_Sort_Tree继承了Binary_Tree。
(1).定义一个Tree的引用做参数的函数,在函数中访问show()函数,通过三种不同的对象来调用该函数以实现多态性。
(2).定义一个Tree的指针做参数的函数,在函数中访问show()函数,通过三种不同对象的地址来调用该函数以实现多态性。
(3).定义一个Tree类的指针,通过new操作产生不同的对象,然后delete该指针,观察虚析构实现的多态性。
Tree.h
#ifndef SHIYANLIU_TREE_H
#define SHIYANLIU_TREE_H
#include<iostream>
using namespace std;
class Tree {
public:
virtual void show();
//virtual void show()=0;
virtual ~Tree();
};
#endif //SHIYANLIU_TREE_H
Tree.cpp
#include "Tree.h"
Tree::~Tree()
{
cout<<"析构一个树对象!"<<endl;
}
void Tree::show()
{
cout<<"树是一个非常重要的数据结构"<<endl;
}
Binary_Tree.h
#ifndef SHIYANLIU_BINARY_TREE_H
#define SHIYANLIU_BINARY_TREE_H
#include<iostream>
#include"Tree.h"
using namespace std;
class Binary_Tree :public Tree
{
public :
virtual void show();
virtual ~Binary_Tree();
};
#endif //SHIYANLIU_BINARY_TREE_H
Binary_Tree.cpp
#include "Binary_Tree.h"
Binary_Tree::~Binary_Tree() noexcept
{
cout<<"析构一个二叉树对象!"<<endl;
}
void Binary_Tree::show()
{
cout<<"二叉树每个节点至多有两颗子树,且有左右之分!"<<endl;
}
Binary_Sort_Tree.h
#ifndef SHIYANLIU_BINARY_SORT_TREE_H
#define SHIYANLIU_BINARY_SORT_TREE_H
#include<iostream>
#include"Binary_Tree.h"
using namespace std;
class Binary_Sort_Tree:public Binary_Tree//二叉排序树
{
public:
virtual void show();
virtual ~Binary_Sort_Tree();
};
#endif //SHIYANLIU_BINARY_SORT_TREE_H
Binary_Sort_Tree.cpp
#include "Binary_Sort_Tree.h"
Binary_Sort_Tree::~Binary_Sort_Tree()
{
cout<<"析构一个二叉排序树对象!"<<endl;
}
void Binary_Sort_Tree::show()
{
cout<<"二叉排序树首先是一颗二叉树!"<<endl;
cout<<"如果左子树不空,左子树小于根节点!"<<endl;
cout<<"如果右子树不空,右子树大于根节点!"<<endl;
}
main.cpp
#include <iostream>
#include"Tree.h"
#include"Binary_Tree.h"
#include"Binary_Sort_Tree.h"
using namespace std;
void show(Tree &tree)
{
tree.show();
cout<<"*************"<<endl;
}
void show1(Tree *tree)
{
tree->show();
cout<<"*************"<<endl;
}
void test0()
{
Tree t1;
show(t1);
Binary_Tree b1;
show(b1);
Binary_Sort_Tree bs1;
show(bs1);
cout<<endl<<"------------------"<<endl;
Tree t2;
Binary_Tree b2;
Binary_Sort_Tree bs2;
show1(&t2);
show1(&b2);
show1(&bs2);
cout<<endl<<"------------------"<<endl;
}
int main() {
//test0();
Tree *t3 = new Tree();
delete(t3);
Tree *t4 = new Binary_Tree();
delete(t4);
Tree *t5 = new Binary_Sort_Tree();
delete(t5);
cout<<endl<<"------------------"<<endl;
}