【代码1】
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
/*
version: 1.0 author: hellogiser blog: http://www.cnblogs.com/hellogiser date: 2014/9/22 */ #include "stdafx.h" #include "iostream" #include <assert.h> using namespace std; void print(const char *str) { cout << str << endl; } class A { public: A() { p(); } virtual void p() { print("A"); } virtual ~A() { p(); } }; class B: public A { public: B() { p(); } void p() { print("B"); } ~B() { p(); } }; int main(int, char **) { A *a = new B(); delete a; } /* A B B A */ |
如果A类的析构函数去掉virtual呢?
【代码2】
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/*
version: 1.0 author: hellogiser blog: http://www.cnblogs.com/hellogiser date: 2014/9/22 */ #include "stdafx.h" #include "iostream" #include <assert.h> using namespace std; void print(const char *str) { cout << str << endl; } class A { public: A() { p(); } virtual void p() { print("A"); } ~A() { p(); // remove virtual } }; class B: public A { public: B() { p(); } void p() { print("B"); } ~B() { p(); } }; int main(int, char **) { A *a = new B(); delete a; } /* A B A */ |