2016-05-15 15 views
3

C++で仮想継承のコンストラクタ呼び出しの順序は何ですか?仮想継承のコンストラクタ呼び出しの順序は?

複数の継承の次の2つのケースについては、

(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 

クラスEの仮想継承と(II):

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

仮想基本クラスが最初に初期化されます。そうでない場合、直接基底クラスは基本クラス宣言の左から右の順序で初期化されます。

クラスの場合、class f: public b, public eは仮想基本クラスがなく、直接ベースクラスbが最初に初期化され、次にeに初期化されます。 (左から右の順)

class f: public b, public virtual e、仮想基本クラスeb次いで、最初に初期化されます。

Initialization orderを参照してください:

1)コンストラクタは、ほとんどの派生クラスのものである場合、仮想基底 クラスは、彼らが 深さ優先の左から右へのトラバースに表示される順序で初期化されていますベースのクラス宣言

2)次に、直接基底クラスが、彼らはこのクラスのベースに現れる ように、左から右へ順に初期化されます(左から右がベース指定子リストの外観を指します) -specifierリスト

3)次に、非静的データメンバーは、クラス定義の 宣言の順番で初期化されます。

4)最後に、コンストラクタの本体が実行されます。

関連する問題