任务:实现一个表示安全数组的类。它应该:存储有关元素数量的信息,在超出范围的情况下抛出异常,并在创建时使用默认值初始化所有元素。
做了什么:我实现了这样的数组类:
#if !defined(ARRAY_WRAPPER_H)
#define ARRAY_WRAPPER_H
#include <stdlib.h>
#include <string>
using namespace std;
template<class T> class ArrayWrapper {
private:
T* array;
int size;
public:
ArrayWrapper(int size): size(size) {
array = new T[size];
for(int i = 0; i < size; i++) array[i] = 0;
}
~ArrayWrapper() {
delete [] array;
}
T get(int index) {
if(index < 0 || index >= size) throw IndexOutOfBoundsException(index, size);
return array[index];
}
void set(int index, T value) {
if(index < 0 || index >= size) throw IndexOutOfBoundsException(index, size);
array[index] = value;
}
int getSize() {
return size;
}
class IndexOutOfBoundsException {
private:
string message;
public:
IndexOutOfBoundsException(int outIndex, int size) {
this->message = "Size array = " + to_string(size) + ". Your index = ";
this->message += to_string(outIndex);
}
string getMessage() {
return message;
}
};
};
#endif
什么不起作用:最后一个要求出现了问题 - 使用默认值初始化数组。如果您将指向某种类型或原语之一(例如
ArrayWrapper<int>, ArrayWrapper<MyClass*>)的指针作为模板参数传递,则没有问题。对于这些情况,默认初始化是这样的:
for(int i = 0; i < size; i++) array[i] = 0;
作品。但是对于这样的情况 -ArrayWrapper<string>我自然会得到一个编译错误。
问:怎么画线
for(int i = 0; i < size; i++) array[i] = 0;
在像 ArrayWrapper 这样的情况下没有实现(或根本不存在)。如果我没记错的话,这应该使用宏来完成,但我不知道具体是怎么做的。请帮助解决问题。
对类型使用默认初始化(我不记得确切的术语 - 零初始化或其他东西......) - 即
对于指针,它将是
nullptr,对于字符串 - 一个空字符串,对于int- 零......或者 - 更简单:
您需要为 type 实现模板类专业化
std::string:为了不重新实现 get / set 之类的方法,最好将它们的实现移动到一个类
ArrayWrapperBase中,并将其作为基类ArrayWrapper及其特化。PS 如果您打算将此容器用于具有默认构造函数的类型,@Harry 的选项更适合您。