虚析构函数
2015-06-08 18:33
489 查看
#include <iostream> using namespace std; class A { public: A() { cout << "构造A!" << endl; }; virtual ~A() { cout << "析构A!" << endl; }; virtual void DoSomething() { cout << "A的DoSomething!" << endl; }; }; class B : public A { public: B() { cout << "构造B!" << endl; }; ~B() { cout << "析构B!" << endl; }; void DoSomething() { cout << "B的DoSomething!" << endl; }; }; int main() { A *Test1 = new A; cout << "**************" << endl; Test1->DoSomething(); cout << "**************" << endl; delete Test1; cout << "**************" << endl; B *Test2 = new B; cout << "**************" << endl; Test2->DoSomething(); cout << "**************" << endl; delete Test2; cout << "**************" << endl; A *Test3 = new B; cout << "**************" << endl; Test3->DoSomething(); cout << "**************" << endl; delete Test3; return 0; }
运行结果:
修改代码,删除virtual
1 #include <iostream> 2 3 4 using namespace std; 5 6 class A 7 { 8 public: 9 A() { cout << "构造A!" << endl; }; 10 ~A() { cout << "析构A!" << endl; }; 11 12 virtual void DoSomething() { cout << "A的DoSomething!" << endl; }; 13 }; 14 15 class B : public A 16 { 17 public: 18 B() { cout << "构造B!" << endl; }; 19 ~B() { cout << "析构B!" << endl; }; 20 21 void DoSomething() { cout << "B的DoSomething!" << endl; }; 22 }; 23 24 int main() 25 { 26 A *Test1 = new A; 27 cout << "**************" << endl; 28 Test1->DoSomething(); 29 cout << "**************" << endl; 30 delete Test1; 31 cout << "**************" << endl; 32 B *Test2 = new B; 33 cout << "**************" << endl; 34 Test2->DoSomething(); 35 cout << "**************" << endl; 36 delete Test2; 37 cout << "**************" << endl; 38 A *Test3 = new B; 39 cout << "**************" << endl; 40 Test3->DoSomething(); 41 cout << "**************" << endl; 42 delete Test3; 43 return 0; 44 }
运行结果:
如果是: B b;
运行结果:
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++中拷贝构造函数的应用详解
- C++中引用(&)的用法与应用实例分析
- C++使用CriticalSection实现线程同步实例
- C++智能指针实例详解
- 解析C++ 浮点数的格式化输出