码迷,mamicode.com
首页 > 其他好文 > 详细

析构函数和虚析构函数

时间:2015-06-08 19:30:06      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 #include <iostream>  
 2 
 3 
 4 using namespace std;
 5 
 6 class A
 7 {
 8 public:
 9     A() { cout << "构造A!" << endl; };
10     virtual ~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 }
View Code

运行结果:

技术分享

修改代码,删除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 }
View Code

运行结果:

技术分享

如果是是

B b;

技术分享

结果:

技术分享

 

析构函数和虚析构函数

标签:

原文地址:http://www.cnblogs.com/xllzzn/p/4561668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!