虚祈构函数
来源:互联网 发布:java分布式面试题 编辑:程序博客网 时间:2024/06/06 02:50
class base
{
public:
base(){}
~base(){ cout<<"hello , I am the base!"<<endl;}
virtual void fun()
{
cout<<"base::fun()"<<endl;
}
};
class derived : public base
{
public:
derived(){}
~derived(){ cout<<"hello , I am the derived!"<<endl; }
void fun()
{
cout<<"derived::fun()"<<endl;
}
};
base *p = new derived;
p->fun();
delete p;
上面的程序运行结果是:
derived::fun()
hello , I am the base!
我们可以看到父类指针要删除子类对象时,子类的祈构函数没有被调用,这造成了子类祈构函数所要完成的功能不能实现(如释放内存资源)。解决上述问题的方法是将父类的祈构函数定义成虚祈构函数,即在前加上关键字virtual。
class base
{
public:
base(){}
virtual ~base(){ cout<<"hello , I am the base!"<<endl;}
virtual void fun()
{
cout<<"base::fun()"<<endl;
}
};
class derived : public base
{
public:
derived(){}
~derived(){ cout<<"hello , I am the derived!"<<endl; }
void fun()
{
cout<<"derived::fun()"<<endl;
}
};
base *p = new derived;
p->fun();
delete p;
运行结果为:
derived::fun()
hello , I am the derived!
hello , I am the base!
所以我们往往将父类的祈构函数定义为虚祈构函数,非父类中我们就不要定义虚祈构函数了,因为存在虚函数,编译器就会给该类建一个虚函数表,这样就不必要的增大了类所占的空间,还有可能降低其可移植性。
- 虚祈构函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- 函数
- python递归遍历文件夹检查文件
- 归并排序之我见
- 关于继承的不完整总结
- The Architecture of Open Source Applications: Nginx
- 一个精明主妇写的省钱过日子的好贴
- 虚祈构函数
- C#中的接口与类的区别
- jQuery学习笔记
- 传说中的《程序猿装B指南》
- 字符集和字符编码(Charset & Encoding)(转)
- 内部类详解
- 【php】文件上传函数,返回值为文件在服务器端的相对地址
- iconv 批量更改文件字符集 uft-8
- 日期格式转换