2016-05-15 77 views
3

C++中虛擬繼承中構造函數調用的順序是什麼?虛擬繼承中構造函數調用的順序是什麼?

對於以下兩種情況的多重繼承; (I)爲下面的代碼,沒有虛擬繼承;

class a 
{ 
    public: 

     a() 
     { 
      cout<<"\t a"; 
     } 

}; 

class b: public a 
{ 
    public: 
     b() 
     { 
      cout<<"\t b"; 
     } 

}; 

class c: public b 
{ 
    public: 

     c() 
     { 
      cout<<"\t c"; 
     } 

}; 

class d: public c 
{ 
    public: 

     d() 
     { 
      cout<<"\t d"; 
     } 
}; 

class e: public c, public d 
{ 
    public: 

     e() 
     { 
      cout<<"\t e"; 
     } 
}; 

class f: public b, public e 
{ 
    public: 

     f() 
     { 
      cout<<"\t f"; 
     } 
}; 


int main() 
{ 

    f aaa; 

    return 0; 
} 

輸出是:

 a  b  a  b  c  a  b  c  d  e  f 

(ii)與E級的虛擬繼承:

class a 
{ 
    public: 

     a() 
     { 
      cout<<"\t a"; 
     } 

}; 

class b: public a 
{ 
    public: 
     b() 
     { 
      cout<<"\t b"; 
     } 

}; 

class c: public b 
{ 
    public: 

     c() 
     { 
      cout<<"\t c"; 
     } 

}; 

class d: public c 
{ 
    public: 

     d() 
     { 
      cout<<"\t d"; 
     } 
}; 

class e: public c, public d 
{ 
    public: 

     e() 
     { 
      cout<<"\t e"; 
     } 
}; 

class f: public b, public virtual e 
{ 
    public: 

     f() 
     { 
      cout<<"\t f"; 
     } 
}; 


int main() 
{ 

    f aaa; 

    return 0; 
} 

輸出是:

 a  b  c  a  b  c  d  e  a  b  f 

有人能解釋如何在兩種情況下都可以獲得輸出結果? 虛擬繼承如何影響對象的構造?

回答

2

虛擬基類將首先被​​初始化,否則直接基類將按照基類聲明從左到右的順序進行初始化。

對於等級fclass f: public b, public e,沒有虛擬基類,直接基類b將首先初始化,然後e。 (從左到右的順序)

對於class f: public b, public virtual e,虛擬基類e將首先初始化,然後b

參見Initialization order

1)如果構造爲最派生類,虛基 類在它們出現在 深度優先左到右的遍歷順序初始化基本的類聲明 (左到右是指在基本符列表外觀)

2)然後,直接基類是在左到右的順序出現在這個類的基數被初始化爲 - 規格表

3)然後,按類定義中的 聲明對非靜態數據成員進行初始化。

4)最後,執行構造函數的主體