若有以下程序: #include<iostream> using namespace std; class Base { public: Base() { x=0; }

admin2009-02-15  25

问题 若有以下程序:
   #include<iostream>
   using namespace std;
    class Base
   {
   public:
     Base()
     {
       x=0;
     }
     int x;
   };
   class Derived1:virtual public Base
   {
   public:
     Derived1()
     {
       x=10;
     }
   };
   class Derived2:virtual public Base
   {
   public:
     Derived2()
     {
      x=20;
     }
   };
   class Derived:public Derived1, protected Derived2
   {    };
   int main()
   {
     Derived obj;
     cout<<obj.x<<end1;
     return 0;
   }
   该程序运行后的输出结果是【  】。

选项

答案20

解析 本题考核虚基类。本题中,虽然Derived1和Derived2都是由共同的基类x派生而来的,但由于引入了虚基类,使得它们分别对应基类的不同副本。这时数据成员x只存在一份拷贝,不论在类Derived1修改,还是在类Derived2中修改,都是直接对这惟一拷贝进行操作。本题程序执行语句“Derived obj”时,就会先调用虚基类 Base的构造函数,使得x=0,然后执行类Derived1的构造函数使得x=10,再执行类 Derived2的构造函数,使得x=20。最后输出x的值为20。
转载请注明原文地址:https://kaotiyun.com/show/pzjp777K
0

最新回复(0)