问题
填空题
有以下程序 #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; } 运行后的打印结果是______。
答案
参考答案:B
解析: 本题考核基类指针与派生类指针的使用。本例程序中类Derived是从基类Base公有继承来的。main()中定义了基类对象b和一个基类指针pb,又定义了派生类Derived的对象d。由于Derived是Base的子类型,因此可以将派生类Derived的对象d的地址赋值给指向基类Base的指针pb,但这时指针pb只能使用从基类Base继承的成员。所以通过对象指针Pb调用的show函数是基类的成员函数show(),从而输出基类私有数据成员a的值2。