设计一个类似数组的类:
customarray.h
#ifndef CUSTOMARRAY_H
#define CUSTOMARRAY_H
template<class T>
class CustomArray
{
public:
CustomArray(): m_data(0), m_size(0) {}
CustomArray(unsigned size): m_size(size), m_data(new T[size]) {}
~CustomArray() { delete[] m_data; }
const T& operator[](unsigned n) const
{
//防止溢出,健壮性
//因为n是unsigned类型,所以不会 < 0
if (n >= m_size || m_data == 0)
throw "Array subscript out of range.";
return m_data[n];
}
T& operator[](unsigned n)
{
if (n >= m_size || m_data == 0)
throw "Array subscript out of range.";
return m_data[n];
}
operator const T*() const
{
return m_data;
}
operator T*()
{
return m_data;
}
private:
T* m_data;
unsigned m_size;
//禁止 复制拷贝 以及 “=”赋值
CustomArray(const CustomArray&);
CustomArray& operator=(const CustomArray&);
};
#endif // CUSTOMARRAY_H
main.cpp
#include <iostream>
#include "customarray.h"
using namespace std;
int main(void)
{
CustomArray<int> array(20);
for (int i=0; i<20; i++)
{
array[i] = i;
}
for (int j=0; j<20; j++)
{
if (j%10 == 0)
cout << endl;
if (array[j] < 10)
cout << "0";
cout << array[j] << " ";
}
cout << endl;
return 0;
}
运行结果:
00 01 02 03 04 05 06 07 08 09
10 11 12 13 14 15 16 17 18 19