有以下程序 #include <iostream> #include <string> using namespace std; class base { private: char baseName[10];

admin2010-06-06  22

问题 有以下程序    #include <iostream>    #include <string>    using namespace std;    class base    {    private:      char baseName[10];    public:      base ()      {        strcpy(baseName,"Base");      }      virtual char *myName()      {        return baseName;      }      char *className()      {        return baseName;      }    };    class Derived : public base    {    private:      char derivedName[10];    public:      Derived()      {        strcpy(derivedName,"Derived");      }      char *myName()      {        return derivedName;      }      char *className()      {        return derivedName;      }    };    void showPtr(base &p)    {      cout<<p.myName () <<" "<<p.className ();    }    int main ()    {      base bb;      Derived dd;      showPtr(dd);      return 0;    }    运行后的输出结果为

选项 A、Derived Base
B、Base Base
C、Derived Derived
D、Base Derived

答案A

解析 本题考核虚函数的应用。类Derived是从基类Base公有派生而来的。因此,Derived是基类Base的子类型。main()函数中定义了一个基类对象bb和一个派生类对象dd。从程序,中可看出派生类Derived的对象dd交给了处理基类Base的对象的函数showPtr进行处理。由于在基类中函数myName被定义成虚函数。所以在函数 showPtr中调用的myName函数为派生类的成员函数 myName,从而输出Derived。然后输出className,即基类名称Base。
转载请注明原文地址:https://kaotiyun.com/show/Jajp777K
0

最新回复(0)