条款七 为多态基类声明virtual析构函数
1.如果基类中的成员函数是virtual类型的,其继承类中相应的函数也是virtual类型,并且基类对象的引用指向继承类对象时,
基类就可以调用继承类函数,否则调用的是基类函数
class base { public: virtual void fun(){ printf("base fun");} }; class derived:public base { public: void fun(){ printf("derived fun");} }; derived der; base &b = der; //或者base *b = &der; b.fun(); //或者b->fun(); 输出的结果是 derived fun;调用的是子类的函数 //注意是在基类引用指向子类对象时才行; base b = der; 这个不行
2.virtual析构函数有什么用? 如
base * get()
{
derived * p = new derived;
return p;
}
这样base类就可以调用子类函数,最后要释放new出来的内存
base *ba = get();
delete ba;
因为base类的析构函数不是virtual类型的,所以delete ba这一边中只能调用基类的析构函数,无法调用子类的析构函数,
这可能导致子类内存无法释放完毕
所以在基类中的析构函数定义为virtual类型,这样delete ba时就可以调用子类的析构函数
3.关于虚函数表的详细介绍,看链接 http://blog.csdn.net/haoel/article/details/1948051
#include <iostream> using namespace std; class base { public: void fun1(){ cout << "base fun1" << endl;} virtual void fun2(){ cout << "base fun2" << endl;} virtual ~base(){ cout << "base的析构函数 " << endl;} //注意virtual的析构函数的意义 }; class derived:public base { public: void fun1(){ cout << "derived fun1" << endl;} virtual void fun2(){ cout << "derived fun2" << endl;} virtual ~derived(){ cout << "derived的析构函数" << endl;} }; base* get() { derived *der = new derived; return der; } int _tmain(int argc, _TCHAR* argv[]) { derived d; //base * b = &d; base *b = get(); b->fun1(); b->fun2(); delete b; return 0; }