c++虚函数和纯虚函数的区别
多态是C++的重要特性,通过基类指针来访问派生类的函数。
虚函数就是为了实现这功能而定义的函数,虚函数可以在定义时实现也可以不实现,定义了虚函数的类可以实例化。
纯虚函数更多的是表示接口的含义,纯虚函数定义时不能实现,需要在派生的子类中实现且必须实现,含有纯虚函数的类不能实例化。
虚析构函数与虚函要成对出现,以便在通过基类指针释放派生对象时,调用派生类的析构函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class VirtualFun { public: VirtualFun(){std::cout<<"create VirtualFun"<<std::endl;}; virtual ~VirtualFun(){std::cout<<"delete VirtualFun"<<std::endl;}; virtual void Hello() {std::cout<<"hello VirtualFun"<<std::endl;}; }; class PureVirtualFun { public: PureVirtualFun(){std::cout<<"create PureVirtualFun"<<std::endl;}; virtual ~PureVirtualFun(){std::cout<<"delete PureVirtualFun"<<std::endl;}; virtual void Hello() = 0; }; class APureVirtualFun : public PureVirtualFun { public: APureVirtualFun(){std::cout<<"create APureVirtualFun"<<std::endl;}; ~APureVirtualFun(){std::cout<<"delete APureVirtualFun"<<std::endl;}; void Hello() {std::cout<<"hello APureVirtualFun"<<std::endl;}; }; int main() { VirtualFun * a = new VirtualFun(); a->Hello(); PureVirtualFun* b = new APureVirtualFun(); b->Hello(); delete a; delete b; } |