- 异常是类 可以自己创建
- 异常派生
- 异常中的数据:数据成员
- 按引用传递异常
#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 xBoundary{};
class xSize{
public:
xSize() {}
xSize(int size):itsSize(size){};
~xSize(){}
int GetSize() { return itsSize; }
virtual void PrintError()
{
cout << "下标发送错误:"<< itsSize << endl;
}
protected:
int itsSize;
};
class xZero : public xSize{
public:
xZero(int size) : xSize(size){}
virtual void PrintError()
{
cout << "下标不能是0!" << endl;
}
};
class xNegative : public xSize{
public:
xNegative(int size): xSize(size){}
virtual void PrintError()
{
cout << "下标不能为负!:" << endl;
}
};
class xTooSmall : public xSize{
public:
xTooSmall(int size): xSize(size){};
virtual void PrintError()
{
cout << "下标不能小于10!" << endl;
}
};
class xTooBig : public xSize{
public:
xTooBig(int size) : xSize(size){}
virtual void PrintError()
{
cout << "下标不能大于10!" << endl;
}
};
private:
int *pType;
int itsSize;
};
int &Array::operator[] (int offSet)
{
int size = this->GetitsSize();
if(offSet >= 0 && offSet < size)
return pType[offSet];
throw xBoundary();
}
Array::Array(int size) : itsSize(size)
{
if (size == 0)
throw xZero(size);
else if (size < 10)
throw xTooSmall(size);
else if (size > 30000)
throw xTooBig(size);
else if (size < 0)
throw xNegative(size);
pType = new int[size];
for(int i = 0; i < size; i++)
pType[i] = 0;
}
int main()
{
try{
Array a;
Array intArray(20);
Array b(50);
for(int j=0; j<100; j++)
{
intArray[j] = j;
cout << "intArray[" << j << "] okey..." << endl;
}
}
catch(Array::xBoundary)
{
cout << "下标越界了" << endl;
}
catch(Array::xSize& exp)
{
exp.PrintError();
}
cout << "test" << endl;
return 0;
}