为什么要有虚析构函数?因为在实现多态时,当用基类操作派生类,在析构时防止只析构基类而不析构派生类的状况发生。
/* 多态 虚析构函数 programmer:qpz time:2014-11-05 */ #include <iostream> const int MAX=3; using namespace std; class Base{ private: int i; public: Base(void){ // this->i=i; } void virtual sbsb(void)=0; virtual ~Base(){ cout<<"~Base"<<endl; } }; class my:public Base{ public: void sbsb(void){ cout<<"mymymyymy"<<endl; } ~my(){ cout<<"~my"<<endl; } }; class you:public Base{ public: void sbsb(void){ cout<<"youyouyou"<<endl; } ~you(){ cout<<"~you"<<endl; } }; class her:public Base{ public: void sbsb(void){ cout<<"her"<<endl; } ~her(){ cout<<"~her"<<endl; } }; int main(void) { Base *a[MAX]={new my(),new you(),new her()}; for(int i=0;i<3;i++){ a[i]->sbsb(); delete a[i]; } return 0; }
一个多态的实践
#include "stdafx.h" #include <iostream> using namespace std; class CPerson { public: CPerson(int iAge, char* sName) { this->iAge = iAge; strcpy_s(this->sName,32,sName);//安全的拷贝函数 } virtual char* WhoAmI() { return "I'm a person"; } private: int iAge; char sName[32]; }; class CWorker :public CPerson { public: CWorker(int iAge, char *sName, char *sEmploymentStatus) :CPerson(iAge, sName) { strcpy_s(this->sEmploymentStatus, 32, sEmploymentStatus); } virtual char* WhoAmI() { return "I'm a Worker"; } private: char sEmploymentStatus[32]; }; class CStudnet :public CPerson { public: CStudnet(int iAge, char *sName,char *sStudentIdentityCard):CPerson(iAge,sName) { strcpy_s(this->sStudentIdentityCard, 32, sStudentIdentityCard); } virtual char* WhoAmI() { return "I'm a Student"; } private: char sStudentIdentityCard[32]; }; /* 面向对象之方法的重载 */ int _tmain(int argc, TCHAR* argv[]) { CPerson cperson(10, "John"); CWorker cworker(35,"Mary","On wacation"); CStudnet cstudent(18, "pp", "Phisician"); cout << cperson.WhoAmI() << endl; cout << cworker.WhoAmI() << endl; cout << cstudent.WhoAmI() << endl; cin.get(); return 0; }