一般类是不写成虚析构函数的。除非你要使用多态的性质。对于一个没有多态性质的类结构而言。子类析构可能会导致父类析构。
// TestRef.cpp : Defines the entry point for the console application. // #include <iostream> #include <string> using namespace std; class A { protected: string _name; public: A(string name):_name(name) { } ~A(){cout << _name << "destruct A" <<endl;} }; class B: public A { public: B(string name):A(name){} ~B(){cout << _name << "destruct B" <<endl;} }; int main(int argc, char* argv[]) { // 这里bb析构时不光会调用~B()也会调用~A() // 因为这里没有使用到多态的性质。 B bb("I am b "); A aa("I am a "); //以下两行函数使用到了多态性质。 A* x = new B("I am x "); delete x; return 0; }
main中最下几行使用到多态性质,所以你运行上面的代码仅仅调用了~A()。因为A中的析构函数并不是virtual类型的。如果你将A中的析构函数前加上virtual关键字,delete时就会先调~B(),再调~A().
析构虚函数和其他的虚函数的不一致的地方在于它不再参照相同的函数签名,而仅仅是每个类中唯一的析构函数。