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

admin2009-02-15  28

问题 有以下程序
   #include <iostream>
   using namespace std;
   class Base
      int a;
   public:
      Base(int x){ a=x;}
     void show(){cout<<a; }
    };
     class Derived: public Base
    {
        int b;
     public:
        Derived(int i):Base(i+1),b(i) { }
        void show(){ cout<<b; }
    };
     int main()
    {
        Base b(5),*pb;
        Derived d(1);
        pb=&d;
        pb->show();
        return 0;
    }
     运行后的打印结果是【  】。

选项

答案2

解析 本题考核基类指针与派生类指针的使用。本例程序中类Derived是从基类 Base公有继承来的。main()中定义了基类对象b和一个基类指针pb,又定义了派生类Derived的对象d。由于Derived是Base的子类型,因此可以将派生类Derived的对象d的地址赋值给指向基类Base的指针pb,但这时指针pb只能使用从基类Base继承的成员。所以通过对象指针pb调用的show函数是基类的成员函数show(),从而输出基类私有数据成员a的值2。
转载请注明原文地址:https://kaotiyun.com/show/ZOkp777K
0

相关试题推荐
最新回复(0)