有以下程序: #include <iostream> using namespace std; class Base { public: Base(){} virtual void f1()

admin2010-03-29  25

问题 有以下程序:    #include <iostream>    using namespace std;    class Base    {    public:       Base(){}       virtual void f1()       {          cout<<"f1 of base"<<end1;       }       ~Base(){}    };    class Derive: public Base    {    public:       void fl(int x)       {          cout<<"f1 of derive"<<end1;       }    };    int main ( )    {       Base *p;       Derive obj1;       p=&obj 1;       p->f1 ( );       return 0;    }

选项 A、编译时出错
B、f1 of derive
C、f1 of base
D、以上答案都不对

答案2

解析 本程序中,将基类的成员函数n()定义为虚函数,而函数f1()在派生类中被重新定义,重定义的函数仍然是一个虚函数。在C++中,一个基类指针(或引用)可以指向它的派生类对象,而且通过这样的指针或引用调用虚函数时,被调用的是该指针(或引用)实际所指向的对象类的那个重定义版本。
转载请注明原文地址:https://kaotiyun.com/show/EXjp777K
0

最新回复(0)