1 #include<iostream> 2 using namespace std; 3 4 class Base1 5 { 6 public: 7 Base1() 8 { 9 cout << "class Base1" << endl; 10 } 11 }; 12 13 class Base2 14 { 15 public: 16 Base2() 17 { 18 cout << "class Base2" << endl; 19 } 20 }; 21 22 class Level1:public Base2,virtual public Base1 23 { 24 public: 25 Level1() 26 { 27 cout << "class Level1" << endl; 28 } 29 }; 30 31 class Level2:public Base2,virtual public Base1 32 { 33 public: 34 Level2() 35 { 36 cout << "class Level2" << endl; 37 } 38 }; 39 40 class TopLevel:public Level1,virtual public Level2 41 { 42 public: 43 TopLevel() 44 { 45 cout << "class TopLevel" << endl; 46 } 47 }; 48 49 int main() 50 { 51 TopLevel obj; 52 } 执行结果 class Base1class Base2class Level2class Base2class Level1class TopLevel 结论:虚基类的构造函数优先执行
时间: 2024-11-05 12:15:44