题目:设计一个数组类MyArray,重载【】操作,数组初始化时,对数组的个数进行检查;
情况:1.index < 0时,抛出异常类eNagetive();
2.index = 0时,抛出异常类eZero();
3.index > 1000时,抛出异常类eTooBig();
4.index < 10 && index >0 时,抛出异常类eTooSmall();
#include <iostream>
using namespace std;
class MyArray
{
int m_length;
int *m_data;
public:
MyArray();
MyArray(int length);
int Getlength();
~MyArray();
int &operator [](int index);
class eSize
{
protected:
const char *ErrMsg;
public:
eSize(const char *ptr):ErrMsg(ptr)
{
}
virtual const char *print() = 0;
};
class eNagetive : public eSize
{
public:
eNagetive():eSize("eNagetive Exception")
{
}
const char *print()
{
return ErrMsg;
}
};
class eZero : public eSize
{
public:
eZero():eSize("eZero Exception")
{
}
const char *print()
{
return ErrMsg;
}
};
class eTooBig: public eSize
{
public:
eTooBig() : eSize("eTooBig Exception")
{
}
const char *print()
{
return ErrMsg;
}
};
class eTooSmall : public eSize
{
public:
eTooSmall():eSize("eTooSmall Exception")
{
}
const char *print()
{
return ErrMsg;
}
};
};
MyArray::MyArray()
{
m_data = NULL;
}
MyArray::MyArray(int length)
{
m_length = length;
m_data = new int[m_length];
if(m_length < 0)
{
throw eNagetive();
}
else if(m_length == 0)
{
throw eZero();
}
else if(m_length > 1000)
{
throw eTooBig();
}
else if(m_length > 0 && m_length <= 10 )
{
throw eTooSmall();
}
}
int MyArray::Getlength()
{
return m_length;
}
MyArray::~MyArray()
{
delete []m_data;
}
int &MyArray::operator [](int index)
{
return m_data[index];
}
int main(int argc, char **argv)
{
try
{
MyArray A(10000);
for(int i = 0;i < A.Getlength() ; i++)
{
A[i] = i;
}
}
catch(MyArray::eNagetive &e)
{
cout << e.print() << endl;
}
catch(MyArray::eZero &e)
{
cout << e.print() << endl;
}
catch(MyArray::eTooSmall &e)
{
cout << e.print() << endl;
}
catch(MyArray::eTooBig &e)
{
cout << e.print() << endl;
}
return 0;
}