问题 填空题

如果不使用多态机制,那么通过基类的指针虽然可以指向派生类对象,但是只能访问从基类继承的成员。下列程序没有使用多态机制,其输出结果是______。
#include<iostream>
using namespace std;
class Base
public:
void print() cout<<’B’;;
class Derived:public Base
public:
void print() cout<<’D’;;
int main()

Derived*pd=new Derived()"
Base*pb=pd;
pb->print();
pd->print();
delete pd;
return 0;

答案

参考答案:BD

解析: 因为本题中的print()函数不是虚函数,所以通过基类指针pb调用的print()函数是基类中的版本,而通过派生类指针pb调用的print()函数是派生类中的版本。因此,程序运行时会先输出一个字符′B′,然后输出字符′D′。

解答题
填空题