#include<iostream> using namespace std; class Biological{ public: virtual void range(){ cout<<"widely"<<endl; } void name(){ cout<<"biological"<<endl; } }; class Animal:public Biological{ public: virtual void range(){ cout<<"medium"<<endl; } void name(){ cout<<"animal"<<endl; } }; class Person:public Animal{ public: virtual void range(){ cout<<"small"<<endl; } void name(){ cout<<"person"<<endl; } }; void Display(Biological *p){ p->range(); p->name(); delete p; } int main(){ Display(new Biological); Display(new Animal); Display(new Person); return 0; }
#include<iostream> using namespace std; class Biological{ public: Biological(){ cout<<"Biological构造"<<endl; } ~Biological(){ cout<<"Biological析构"<<endl; } }; class Animal:virtual public Biological{ public: Animal(){ cout<<"Animal构造"<<endl; } ~Animal(){ cout<<"Animal析构"<<endl; } }; class Plant:virtual public Biological{ public: Plant(){ cout<<"Plant构造"<<endl; } ~Plant(){ cout<<"Plant析构"<<endl; } }; class SeaAnemone:public Animal,public Plant{ public: SeaAnemone(){ cout<<"SeaAnemone构造"<<endl; } ~SeaAnemone(){ cout<<"SeaAnemone析构"<<endl; } }; int main(){ SeaAnemone sea_anemone; return 0; }
#include<iostream> using namespace std; class Biological{ public: Biological(){ cout<<"Biological构造"<<endl; } virtual ~Biological(){ cout<<"Biological析构"<<endl; } private: char *name; }; class Animal:virtual public Biological{ public: Animal(){ cout<<"Animal构造"<<endl; } ~Animal(){ cout<<"Animal析构"<<endl; } }; class Plant:virtual public Biological{ public: Plant(){ cout<<"Plant构造"<<endl; } ~Plant(){ cout<<"Plant析构"<<endl; } }; class SeaAnemone:public Animal,public Plant{ public: SeaAnemone(){ cout<<"SeaAnemone构造"<<endl; } ~SeaAnemone(){ cout<<"SeaAnemone析构"<<endl; } }; int main(){ Biological *sea_anemone = new SeaAnemone; delete sea_anemone; return 0; }
注意:如果将~Biological()函数前的virtual去掉那么函数会出错。
总结:我们一定要注意在基类的析构函数前面加上virtual,使其变成虚析构在C++程序中使用虚函数,虚继承和虚析构是很好的习惯 可以避免许多的问题。
原文:https://www.cnblogs.com/ligei/p/11443857.html