zoukankan      html  css  js  c++  java
  • c++构造析构顺序

    
    class  A
    {
    public:
    	A(){ cout << "constrcut A" << endl; };
    	~A(){ cout << "destruct A" << endl; };
    };
    
    class C
    {
    public:
    	C(){ cout << "construct C" << endl; };
    	~C(){ cout << "destruct C" << endl; };
    };
    
    class B: public A
    {
    public:
    	B(){ cout << "construct B" << endl; };;
    	~B(){ cout << "destruct B" << endl; };
    private:
    	C c;
    };
    
    
    

    执行后结果为:

    constrcut A
    construct C
    construct B
    destruct B
    destruct C
    destruct A
    

    即:生成派生类对象时,先执行父类的构造函数,再执行类成员变量的构造函数(依照声明顺序),最后执行派生类构造函数中的内容。
    即:

    1. 父类的构造函数
    2. 类成员变量的构造函数(依照声明顺序),
    3. 派生类构造函数

    析构顺序相反。

  • 相关阅读:
    java-day21
    java-day20
    java-day19
    java-day18
    java-day17
    java-day16
    java-day15
    java-day14
    python-day06
    java-day13
  • 原文地址:https://www.cnblogs.com/iois/p/4949652.html
Copyright © 2011-2022 走看看