设计一个数组类MyArray,重载【】操作,数组初始化时,对数组的个数进行有效检查。
1、index<0 抛出异常eNegative
2、index=0抛出异常eZero
3、index>1000抛出异常eTooBig
4、index<10抛出异常eTooSmall
5、eSize类是以上类的父类,实现有参数构造、并定义virtual void printfErr()输出错误。
具体实现如下述代码:
#include<iostream>
using namespace std;
class MyArray //创建一个MyArray类
{
private:
int m_len;
int *m_data;
public:
MyArray(int l); //写一个含参的构造函数
~MyArray();
int &operator [](int index) //对[]进行重载
{
return m_data[index];
}
int GetLength()
{
return m_len;
}
class eSize //eSize作为其他异常类的父类
{
protected:
const char *Errmsg;
public:
eSize(char *msg):Errmsg(msg)
{}
void printErr()
{
cout << Errmsg << endl;
}
};
class eNegative : public eSize //eNegative继承于父类eSize 类中类
{
public:
eNegative():eSize("eNegative Exception")
{}
void printErr()
{
cout << Errmsg << endl;
}
};
class eZero : public eSize
{
public:
eZero():eSize("eZero Exception")
{}
void printErr()
{
cout << Errmsg << endl;
}
};
class eTooSmall : public eSize
{
public:
eTooSmall():eSize("eTooSmall Exception")
{}
void printErr()
{
cout << Errmsg << endl;
}
};
class eTOoBig : public eSize
{
public:
eTOoBig():eSize("eTooBig Exception")
{}
void printErr()
{
cout << Errmsg << endl;
}
};
};
MyArray::MyArray(int l) //构造函数
{
m_len=l;
if(m_len<0) //根据题目,抛出数组长度异常
{
throw eNegative();
}
else if(m_len==0)
{
throw eZero();
}
else if(m_len>0&&m_len<=10)
{
throw eTooSmall();
}
else if(m_len>1000)
{
throw eTooBig();
}
m_data=new int[m_len];
}
MyArray::~MyArray()
{
if(m_data!=NULL)
{
delete [] m_data;
}
}
int main()
{
try
{
MyArray a(30);
for(int i=0;i<a.GetLength();i++)
{
a[i]=i;
}
}
catch(MyArray::eNegative &e) //捕获异常
{
cout << "eNegative Exception" << endl;
}
catch(MyArray::eZero &e)
{
cout << "eZero Exception" << endl;
}
catch(MyArray::eTOoBig &e)
{
cout << "eTOoBig Exception" << endl;
}
catch(MyArray::eTooSmall &e)
{
cout << "eTooSmall Exception" << endl;
}
return 0;
}