C++ 构造和析构的顺序

直接用代码说明问题:

1#include <iostream> 2using namespace std; 3 4class A { 5public: 6 A(int a = 0) : _a(a) { cout << "Constructor A!" << _a << endl; } 7 ~A() { cout << "Destrucotr A!" << _a << endl; } 8 9private: 10 int _a; 11}; 12 13class B : public A { 14public: 15 B(int a = 0, int b = 0) : A(a), _b(b) { 16 cout << "Constructor B!" << _b << endl; 17 } 18 ~B() { cout << "Destrucotr B!" << _b << endl; } 19 20private: 21 int _b; 22}; 23 24class D { 25public: 26 D(int d = 0) : _d(d) { cout << "Constructor D!" << _d << endl; } 27 ~D() { cout << "Destrucotr D!" << _d << endl; } 28 29private: 30 int _d; 31}; 32class C : public B, public D { 33public: 34 C(int a = 0, int b = 0, int c = 0, int d = 0) : B(a, b), D(d), _c(c) { 35 cout << "Constructor C!" << _c << endl; 36 } 37 ~C() { cout << "Destrucotr C!" << _c << endl; } 38 39private: 40 int _c; 41}; 42int _tmain(int argc, _TCHAR *argv[]) { 43 B a(6), b(7, 8); 44 C c(1, 2, 3), d(12, 13, 14, 15); 45 return 0; 46} 47 48// OUtput: 49// Constructor A!6// Constructor B!0// Constructor A!7// Constructor 50// B!8// Constructor A!1// Constructor B!2// Constructor D!0// Constructor C!3// 51// Constructor A!12// Constructor B!13// Constructor D!15// Constructor C!14// 52// Destrucotr C!14// Destrucotr D!15// Destrucotr B!13// Destrucotr A!12// 53// Destrucotr C!3// Destrucotr D!0// Destrucotr B!2// Destrucotr A!1// 54// Destrucotr B!8// Destrucotr A!7// Destrucotr B!0// Destrucotr A!6
点赞
收藏

评论区

加载中...

相关推荐

C++ 析构函数与内存池

CPrimer书中也提到编写class时要注意copycontrol成员(拷贝构造函数,赋值操作符,析构函数,C11又多个移动构造函数)。工作时在C和C之间切换,有时就忘记了C的细节(真的好讨厌)。C析构函数与构造函数对应,构造对象时调用构造函数,析构对象时调用析构函数,于是可以在对象的析构函数中释放资

KVM调整cpu和内存

一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid

C++

include<iostreamusingnamespacestd;classGoods{public:Goods()//货物的无参构造{weight0;nextN

C++——Linux——Hello World!

include  //include位置:/usr/includeincludeusingnamespacestd;intmain(){cout<<"HelloWorld"<     return0;}gotesttest.cpp//用ggcc编译会出

C++中构造函数和析构函数

构造函数定义它是一种特殊的方法。主要用来在创建对象时初始化对象,即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中。另外,一个类可以有多个构造函数,我们可以根据其参数个数的不同或参数类型的不同来区分它们(这就是构造函数的重载)特点1.构造函数的命名必须和类名完全相同;2.构造函数的功能主要用于在类的对象创建时定义

C++构造函数调用虚函数的后果

include<iostreamclasscx{public:virtualvoidfunc(){std::cout<<"func"<<std::endl;}cx(){func();//构