c++自定义数组越异常 ArrayIndexOutOfBoundsException (学习)
Posted herd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++自定义数组越异常 ArrayIndexOutOfBoundsException (学习)相关的知识,希望对你有一定的参考价值。
#include <iostream>
using namespace std;
const int DefaultSize = 10;
class Array
public:
Array(int itsSize=DefaultSize);
~Array()
delete[] pType;
//运算符重载
int& operator[](int offset);
const int& operator[](int offset) const;
int GetItsSize() const
return itsSize;
class ArrayIndexOutOfBoundsException ;
class ElementZero;
private:
int *pType;
int itsSize;
;
Array::Array(int size) :itsSize(size)
if (size==0)
throw ElementZero();
pType = new int[size];
for (int i=0;i<size;i++)
pType[i] = 0;
int& Array::operator[](int offset)
int vcsize =GetItsSize();
if (offset>=0 && offset<vcsize)
return pType[offset];
else
throw ArrayIndexOutOfBoundsException();
const int& Array::operator[](int offset) const
int vcsize = this->GetItsSize();
if (offset >= 0 && offset<vcsize)
return pType[offset];
else
throw ArrayIndexOutOfBoundsException();
int main()
Array a;
Array b(12);
b[2] = 10;
cout << b[2]<< endl;
Array arr1(20);
try
for (int k=0;k<100;k++)
arr1[k] = k;
catch (Array::ArrayIndexOutOfBoundsException)
cout<<"Array Index Out Of Bounds Exception..."<<endl;
system("pause");
return 0;
-------------------------------------------------------------------------------------
10
Array Index Out Of Bounds Exception...
请按任意键继续. . .
以上是关于c++自定义数组越异常 ArrayIndexOutOfBoundsException (学习)的主要内容,如果未能解决你的问题,请参考以下文章