C++语言不能够检测数组下标是否越界,如果越界程序就会崩溃。为了检测数组下标越界检测,建立数组模板,可以完成。
在模板中要想获得下标值,需要重载数组下标运算符“[]”,重载数组下标运算符后使用模板类实例化数组,就可以实现下标越界检测。
例如:
#include<cassert>
template<typename T,int b>
class Array
{
T& opertor[](int sub)
{
assert(sub>0&&sub<b);
}
};
具体例子如下:
#include <iostream>
#include <cassert>
#include <iomanip>
using namespace std;
class Date
{
public:
Date(int m=0,int d=0,int y=0)
{
iMonth = m;
iDay = d;
iYear = y;
}
//重载输出
friend ostream& operator<<(ostream& os, const Date t)
{
cout << "Month:" << t.iMonth << ' ';
cout << "Day:" << t.iDay << ' ';
cout << "Year:" << t.iYear << ' ';
return os;
}
~Date()
{}
void Display()
{
cout << "Month:" << iMonth;
cout << "Day:" <<iDay ;
cout << "Year:" << iYear ;
cout << endl;
}
private:
public:
int iMonth;
int iDay;
int iYear;
};
template<typename T,int b>
class Array
{
public:
Array(){}
~Array(){}
T& operator[](int sub)
{
assert(sub >= 0 && sub < b);
return elem[sub];
}
private:
public:
T elem[b];
};
int main(int argc, char *argv[])
{
Array<Date, 3>dateArray;
Date t1(1, 2, 3);
Date t2(4, 5, 6);
Date t3(7, 8, 9);
dateArray[0] = t1;
dateArray[1] = t2;
dateArray[2] = t3;
for (int i = 0; i < 3;++i)
{
cout << dateArray[i] << endl;
}
Date t4(10, 11, 12);
dateArray[3] = t4;
cout << dateArray[3] << endl;
cout<<"....."<<endl;
system("pause");
return 0;
}