C++虚析构函数的作用
来源:互联网 发布:React双向数据绑定原理 编辑:程序博客网 时间:2024/05/21 00:18
1、作用
为了在实现多态的时候不造成内存泄露,
如果基类析构函数前不加vitual,派生类对象被销毁后,只会调用基类的析构函数,而不会去调用派生类的析构函数。
2、对于正常的函数,如果基类中声明为virtual,则派生类可以不用再写virtual
- // CPPTest.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- class Base
- {
- public:
- Base(){}
- virtual ~Base()
- {
- printf("Base Destructor!/n");
- }
- virtual void Func()
- {
- printf("Base Func!/n");
- }
- private:
- int m_iData;
- };
- class Derived : public Base
- {
- public:
- Derived(){}
- ~Derived()
- {
- printf("Derived Destructor!/n");
- }
- void Func()
- {
- printf("Derived Func!/n");
- }
- };
- class Derived2 : public Derived
- {
- public:
- Derived2(){}
- ~Derived2()
- {
- printf("Derived2 Destructor!/n");
- }
- void Func()
- {
- printf("Derived2 Func!/n");
- }
- };
- int main(int argc, char* argv[])
- {
- Base *pb = new Base;
- pb->Func();
- Base *pd = new Derived;
- pd->Func();
- Base *pd2 = new Derived2;
- pd2->Func();
- delete pb;
- delete pd;
- delete pd2;
- return 0;
- }
结果:
Base Func!
Derived Func!
Derived2 Func!
Base Destructor!
Derived Destructor!
Base Destructor!
Derived2 Destructor!
Derived Destructor!
Base Destructor!
0 0
- 【C/C++】C++虚析构函数的作用
- C函数指针的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- Android实现PopupWindow 弹窗效果 可用于提示信息等
- Unable to instantiate service com.baidu.android.pushservice.PushService: java.lang.ClassNotFoundExc
- poco库应用框架
- 安卓关于exported的问题
- phonegap的相关资料
- C++虚析构函数的作用
- flex复选框和下拉列表的几种用法整理http://www.jb51.net/article/39597.htm
- Spring FrameWork 学习总结
- c学习笔记
- String 与StringBuilder
- Paraview与VTK学习笔记(五)
- ContentProvider数据库共享之——读写权限与数据监听
- C# WInform TextChanged MessageBox.Show冲突的临时解决办法
- 11181 - Probability|Given