问题 问答题

使用VC6打开考生文件夹下的工程MyProj2。此工程包含一个源程序文件 MyMain2.cpp,此程序的运行结果为: Derive1’s Print() Called. Derive2’s Print() called. 其中定义的类并不完整,按要求完成下列操作,将类的定义补充完整。 ①定义函数Print()为无值型纯虚函数。请在注释“//**1**”之后添加适当的语句。 ②建立类Derivel的构造函数,请在注释“//**2**”之后添加适当的语句。 ③完成类Derive2成员函数Print()的定义。请在注释“//**3**”之后添加适当的语句。 ④定义类Derivel的对象指针d1,类Derive2的对象指针d2。其初始化值分别为1和2。 源程序文件MyMain2.cpp中的程序清单如下: //MyMain2. cpp #include <iostream> using namespace std; class Base { public: Base(int i) {b=i; } //* * 1 * * protected: int b; }; class Derivel: public Base { public: //* * 2 * * void print () {cout<<" Derivel’s Print() called."<<end1; } }; class Derive2 : public Base { public: Derive2(int i) :Base(i) { } //* * 3 * * }; void fun (Base *obj) { obj->Print (); } int main ( ) { //* * 4 * * fun (d1); fun (d2); return 0; }

答案

参考答案:

解析:①virtual void Print()=0; ②Derivel(int i):Base(i){} ③void Print(){cout<<"Derive2’s Print()called."<<end1;} ④Derivel*d=new Derive1(1);Derive2*d2=new Derive2(2) 本题是一道综合应用题,考核继承与派生,以及纯虚函数。 ①在第1处定义函数Print()为无值型纯虚函数。根据C++中无纯虚函数的定义格式可知在第1处应填入“virtual void Print()=0;”。 ②在第2处建立类Derivel的构造函数,其中还要调用基类的构造函数。所以应填入“Derivel(int i):Base(i){}”。 ③在第3处完成类Derive2成员函数Print()的定义,根据程序的输出可知,此处应填入“void Print(){cout<<"Derive2’s Print() called.”<<end1;}。 ④在第4处定义类Derive1的对象指针d1,类Derive2的对象指针d2,其初始化值分别为1和2。所以应填入“Derive1 *d=new Derive1(1);Derive2 *d2=new Derive2(2)”。

单项选择题
填空题