程序填空题:抽象类和纯虚函数的使用
下面的程序定义了Base1类、Base2类和Derived类。
Base1是一个抽象类,其类体中声明了纯虚函数Show。
Base2类的构造函数负责动态分配一个字符数组,并将形参指向的字符串复制到该数组中,复制功能要求通过调用strcpy函数来实现。
Derived类以公有继承方式继承Base1类,以私有继承方式继承Base2类。在Derived类的构造函数的成员初始化列表中调用Base类的构造函数。
请在空白地方填写适当代码,以完成Base1、Base2和Derived类的功能。
此程序的正确输出结果应为:
I’m a derived class.
```c++
#include
#include
using namespace std;
class Base1 {
public:
//下列语句需要声明纯虚函数Show
@@[virtual void Show() = 0](3);
};
class Base2 {
protected:
char * _p;
Base2(const char *s)
{
_p = new char[strlen(s) + 1];
//下列语句将形参指向的字符串常量复制到该类的字符数组中
@@[strcpy(_p, s)](3);
}
~Base2() { delete [] _p; }
};
//Derived类公有继承Base1,私有继承Base2类
class Derived : @@[public Base1, private Base2](3) {
public:
//以下构造函数调用Base2类构造函数
Derived(const char *s) : @@[Base2(s)](3)
{ }
void Show()
{ cout << _p << endl; }
};
int main()
{
Base1 *pb = new Derived("I'm a derived class.");
pb->Show();
delete pb;
return 0;
}
```
答案:
第1空:virtual void Show() = 0
第2空:strcpy(_p, s)
第3空:public Base1, private Base2
第4空:Base2(s)
Base1是一个抽象类,其类体中声明了纯虚函数Show。
Base2类的构造函数负责动态分配一个字符数组,并将形参指向的字符串复制到该数组中,复制功能要求通过调用strcpy函数来实现。
Derived类以公有继承方式继承Base1类,以私有继承方式继承Base2类。在Derived类的构造函数的成员初始化列表中调用Base类的构造函数。
请在空白地方填写适当代码,以完成Base1、Base2和Derived类的功能。
此程序的正确输出结果应为:
I’m a derived class.
```c++
#include
#include
using namespace std;
class Base1 {
public:
//下列语句需要声明纯虚函数Show
@@[virtual void Show() = 0](3);
};
class Base2 {
protected:
char * _p;
Base2(const char *s)
{
_p = new char[strlen(s) + 1];
//下列语句将形参指向的字符串常量复制到该类的字符数组中
@@[strcpy(_p, s)](3);
}
~Base2() { delete [] _p; }
};
//Derived类公有继承Base1,私有继承Base2类
class Derived : @@[public Base1, private Base2](3) {
public:
//以下构造函数调用Base2类构造函数
Derived(const char *s) : @@[Base2(s)](3)
{ }
void Show()
{ cout << _p << endl; }
};
int main()
{
Base1 *pb = new Derived("I'm a derived class.");
pb->Show();
delete pb;
return 0;
}
```
答案:
第1空:virtual void Show() = 0
第2空:strcpy(_p, s)
第3空:public Base1, private Base2
第4空:Base2(s)