标签:
1 #include <iostream> 2 using namespace std; 3 class A 4 { 5 public: 6 A () 7 { 8 cout<<"A 构造 "<<endl; 9 } 10 virtual ~A() // 定义虚析构函数 导致原来析构顺序发生变化 11 { 12 cout<<"A 析构 "<<endl; 13 } 14 15 }; 16 class B : public A 17 { 18 public: 19 B () 20 { 21 cout<<"B 构造 "<<endl; 22 } 23 ~B () 24 { 25 cout<<"B 析构 "<<endl; 26 } 27 28 }; 29 class C : public B 30 { 31 public : 32 ~C () 33 { 34 cout<<"C 析构 "<<endl; 35 } 36 37 C () 38 { 39 cout<<"C 构造 "<<endl; 40 } 41 };
42 int main(int argc, char *argv[]) 43 { 44 B *b=new C; //由C的构造函数来创建的对象指针b,这一步会说明析构的b的范围最深到c 45 delete b; 46 return 0; 47 }
输出结果:
说明:上面的例子对析构A或者对析构B其中一个或者两个采用虚函数,都会是析构顺序从最深的子类,这个最深由创建对象时候确定,如果
1 #include <iostream> 2 using namespace std; 3 class A 4 { 5 public: 6 A () 7 { 8 cout<<"A 构造 "<<endl; 9 } 10 virtual ~A() 11 { 12 cout<<"A 析构 "<<endl; 13 } 14 15 }; 16 class B : public A 17 { 18 public: 19 B () 20 { 21 cout<<"B 构造 "<<endl; 22 } 23 ~B () 24 { 25 cout<<"B 析构 "<<endl; 26 } 27 28 }; 29 class C : public B 30 { 31 public : 32 ~C () 33 { 34 cout<<"C 析构 "<<endl; 35 } 36 37 C () 38 { 39 cout<<"C 构造 "<<endl; 40 } 41 }; 42 class D : public C 43 { 44 public : 45 ~D () 46 { 47 cout<<"D 析构 "<<endl; 48 } 49 50 D () 51 { 52 cout<<"D 构造 "<<endl; 53 } 54 }; 55 int main(int argc, char *argv[]) 56 { 57 B *b=new C; 58 delete b; 59 return 0; 60 }
那么输出结果跟上面的一样
标签:
原文地址:http://www.cnblogs.com/codeblock/p/4451742.html