#include <iostream> using namespace std; // 集合类的操作接口 class Collection { public: // 向集合中添加一个元素 virtual void add(int e) = 0; // 获取指定位置的元素 virtual int get(unsigned int i) const = 0; }; // 实现了集合接口 class Array : public Collection { public: Array(unsigned int s) { //**********found********** a = new ________________; size = s; num = 0; } ~Array() { //**********found********** _______________; } virtual void add(int e) { if (num < size) { //**********found********** _______________ = e; num++; } } virtual int get(unsigned int i) const { if (i < size) { //**********found********** _______________; } return 0; } private: int *a; unsigned int size; unsigned int num; }; void fun(Collection& col) { int i; for (i = 0; i < 10; i++) { col.add(i+1); } for (i = 0; i < 10; i++) { cout << col.get(i) << ", "; } cout << endl; } int main() { Array a(0xff); fun(a); return 0; }
时间: 2023-06-29 17:16:24 浏览: 54
答案如下:
```c++
a = new int[size];
```
```c++
delete[] a;
```
```c++
a[num] = e;
```
```c++
return a[i];
```
这段代码定义了一个集合类的操作接口 `Collection`,其中包含了向集合中添加一个元素和获取指定位置的元素两个纯虚函数。然后又定义了一个实现了集合接口的类 `Array`,它使用了动态数组来存储元素,并实现了接口中的两个函数。在 `main` 函数中,我们创建了一个 `Array` 对象,并通过一个引用调用 `fun` 函数。`fun` 函数调用了 `Collection` 接口中的函数,而实际上使用的是 `Array` 类中的函数。最终程序输出了 `1, 2, 3, 4, 5, 6, 7, 8, 9, 10,`。
相关问题
#include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; //
这是一段C++程序的头文件部分,包含了一些标准库的头文件,具体介绍如下:
1. iostream:提供了输入输出流的基本功能,如cin、cout等。
2. fstream:提供了文件操作相关的功能,如读写文件等。
3. vector:提供了可变大小数组的功能,可以方便地进行动态管理。
4. string:提供了字符串相关的功能,如字符串的拼接、截取等。
其中,using namespace std; 表示使用标准命名空间,可以简化程序中的代码。
#include <iostream> #include <vector> #include <fstream> using namespace std; #include <boost/timer.hpp>
这段代码是一个C++程序的头文件部分,它包含了三个标准库的头文件和一个boost库的头文件。具体介绍如下:
1. `#include <iostream>`:这是C++标准库中的头文件,用于输入输出操作。它包含了一些常用的输入输出流对象,如`cin`和`cout`。
2. `#include <vector>`:这是C++标准库中的头文件,用于定义和操作动态数组(向量)。`vector`是一个模板类,可以存储任意类型的元素,并提供了方便的方法来访问和修改这些元素。
3. `#include <fstream>`:这是C++标准库中的头文件,用于文件输入输出操作。它提供了一些类和函数,可以方便地读写文件。
4. `#include <boost/timer.hpp>`:这是boost库中的头文件,用于计时器功能。boost是一个流行的C++扩展库,提供了许多高效且易于使用的功能和工具。