P313第四题
#include<iostream>
using namespace std;
template <class T,int n=100>
# define INF 0x3f3f3f3f
class Array
{
int a;
int b;
T test[1000];
public:
Array(int bb)
{
a=0;
b=bb;
}
Array(int aa,int bb)
{
a=aa;
b=bb;
}
T& operator [](int t1)
{
if(t1>=a&&t1<b)
return test[t1-a];
else
return test[t1-a]=INF;
}
};
void testnum(int t)
{
try
{
if(t!=INF)
cout<<t<<endl;
else
throw "wrong";
}
catch( const char *message)
{
cout<<message<<endl;
}
}
int main()
{
Array<int> a(-10,10);//定义一个模板,下标是从 -10到10/
a[-2]=0;
a[11]=10;
testnum(a[-2]);
testnum(a[11]);
return 0;
}
思路二:
还是按照正常的数组进行存储,解释一下,如果定义的模板下标是从-2到2,那么这个时候就可以 int a[4],分别给a[0],a[1],a[2],a[3],a[4]赋值,如果要查询下标为-2的数组中的数,那么这个时候下标为-2的数就代表数组a中的a[0],所以直接输出a[0]即可,下标是-1就输出a[1],以此类推。
错误报告:一开始在catch 函数中并没有加上const,加上之后不报错了。