问:为什么要把父类的析构函数定义成虚函数?
答:否则子类的析构函数可以未被调用,具体代码如下:
class A { public: A(){TRACE("A()/n");}; ~A(){TRACE("~A()/n");}; }; class B : public A { public: B(){TRACE("B()/n");}; ~B(){TRACE("~B()/n");}; }; void CEgDlg::OnButton1() { A * p = (A*)new B() ; delete p ; }
运行结果如下:
A() B() ~A()