C++ 構造,析構順序(靜態對象),構造靜態

來源:互聯網
上載者:User

C++ 構造,析構順序(靜態對象),構造靜態
測試代碼:

#include <iostream>#include <cstdlib>using namespace std;class A{    public:        A(){            cout<<"A - 構造"<<endl;        }        ~A(){            cout<<"A - 析構"<<endl;        }};class B:public A{    public:        B(){            cout<<"B - 構造"<<endl;        }        ~B(){            cout<<"B - 析構"<<endl;        }};class C{    public:        C(){            cout<<"C - 構造"<<endl;        }        ~C(){            cout<<"c - 析構"<<endl;        }};class E{    public:        E(){            cout<<"e - 構造"<<endl;        }        ~E(){            cout<<"E - 析構"<<endl;        }};class D:public E{    public:        D(){            cout<< "D - 構造"<<endl;        }        ~D(){            cout<< "D - 析構"<<endl;        }    private:    C c;    static B b;};B D::b;int main(){    D d;    cout << "Hello world!" << endl;    return 0;}

運行結果如下:


分析:在一個類中,如果存在其他類的成員,先進行構造,若這個類對象是static的,靜態對象是在所有其他對象之前進行構造,若這個靜態對象要是繼承某個父類,應先構造父類,在構造衍生類別,所以 A - 構造;B - 構造;e - 構造(構造自己的父類);c - 構造 ;最後才是 D - 構造;

析構的順序與其相反 進行,靜態函數最後 析構。


測試代碼:不帶static對象:

#include <iostream>#include <cstdlib>using namespace std;class A{    public:        A(){            cout<<"A - 構造"<<endl;        }        ~A(){            cout<<"A - 析構"<<endl;        }};class B:public A{    public:        B(){            cout<<"B - 構造"<<endl;        }        ~B(){            cout<<"B - 析構"<<endl;        }};class C{    public:        C(){            cout<<"C - 構造"<<endl;        }        ~C(){            cout<<"c - 析構"<<endl;        }};class E{    public:        E(){            cout<<"e - 構造"<<endl;        }        ~E(){            cout<<"E - 析構"<<endl;        }};class D:public E{    public:        D(){            cout<< "D - 構造"<<endl;        }        ~D(){            cout<< "D - 析構"<<endl;        }    private:    C c;    B b;};//B D::b;int main(){    D d;    cout << "Hello world!" << endl;    return 0;}

結果如下:


不帶有static對象,先構造自己的父類(若存在),然後構造裡面的成員,c - 構造;B - 構造(A 是父類先構造),最後是自己的建構函式 D - 構造;解構函式與其相反;


總結:析構順序:

1 先執行函數體的析構

2 然後按照聲明順續相反的執行所有非靜態對象的析構

3 執行自己的父析構

4 若有靜態成員對象,則最後析構


構造順序:

1.先構造自己的父類,若是有靜態成員對象,最先構造靜態成員對象的父類,然後是靜態成員對象,在其次是自己父類構造

2.其他非靜態成員對象的構造

3.自己的建構函式


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.