检测数组下标边界是否超出范围
出现错误ror C2440: 'initializing' : cannot convert from 'const int' to 'class Array<int>'
No constructor could take the source type, or constructor overload resolution was ambiguous
G:\调试专业用\c++调试用\检测数组下标越界\arry_detect.cpp(64) : error C2440: 'initializing' : cannot convert from 'const int' to 'class Array<double>'
No constructor could take the source type, or constructor overload resolution was ambiguous
执行 cl.exe 时出错.
请问各位大侠 该如何修改
[code=C/C++][/code]
#include <iostream>
//using namespace std;
template <class T> class Array;
template <class T> class ArrayBody
{
friend class Array <T>;
T* tpBody;
int iROws,iColumns,iCurrentRow;
ArrayBody(int iRsz, int iCsz)
{
tpBody= new T[iRsz*iCsz];
iRows= iRsz; iColumns = iCsz; iCurrentRow = -1;
}
public:
T& operator[](int j)
{
bool row_error,column_error;
row_error=column_error=false;
try
{
if(iCurrentRow <0 || iCurrentRow >= iRows)
row_error = true;
if(j<0 || j >= iColumns)
column_error=false;
if(row_erro== true || column_error == true)
throw 'e';
}
catch(char)
{
if (row_error == true)
cerr<<"行下标越界["<< iCurrentRow<<"]";
if(column_error== true)
cerr<<"列下标越界["<<j<<"]";
cout<<"\n";
}
return tpBody[iCurrentRow*iColumns+j];
}
~ArrayBody(){delete[] tpBody;}
};
template <class T> class Array
{
ArrayBody <T> tBody;
public:
ArrayBody <T> & operator [](int i)
{
tBody.iCurrentRow= I;
return tBody;
}
Array(int iRsz, int iCsz):tBody(iRsz,iCsz){}
};
void main()
{
Array <int> a1=(10,20);
Array <double> a2=(3,5);
int b1;
double b2;
b1 = a1[-5][10];
b1 = a1[10][15];
b1 = a1[1][4];
b2 = a2[2][6];
b2 = a2[10][20];
b2 = a2[1][4];
}
[解决办法]
很多粗心引起的错误啊。如果你是用的是VS编译器,那么我建议你下载个VC Assist插件。很方便,还能帮你解决不少小问题呢。
- C/C++ code
template <class T> class Array;template <class T> class ArrayBody{ friend class Array<T>; T* tpBody; int iRows,iColumns,iCurrentRow; ArrayBody(int iRsz, int iCsz) { tpBody= new T[iRsz*iCsz]; iRows= iRsz; iColumns = iCsz; iCurrentRow = -1; }public: T& operator[](int j) { bool row_error,column_error; row_error=column_error=false; try { if(iCurrentRow <0 || iCurrentRow >= iRows) row_error = true; if(j<0 || j >= iColumns) column_error=false; if(row_error== true || column_error == true) throw 'e'; } catch(char) { if (row_error == true) cerr<<"行下标越界["<< iCurrentRow<<"]"; if(column_error== true) cerr<<"列下标越界["<<j<<"]"; cout<<"\n"; } return tpBody[iCurrentRow*iColumns+j]; } ~ArrayBody(){delete[] tpBody;}};template <class T> class Array{ ArrayBody <T> tBody;public: ArrayBody<T> & operator [](int i) { tBody.iCurrentRow= i; return tBody; } Array(int iRsz, int iCsz):tBody(iRsz,iCsz){}};void main(){ Array<int> a1(10,20); Array<double> a2(3,5); int b1; double b2; b1 = a1[-5][10]; b1 = a1[10][15]; b1 = a1[1][4]; b2 = a2[2][6]; b2 = a2[10][20]; b2 = a2[1][4];}