设计一个数组类MyArray,重载 [ ] 操作(加入异常处理代码throw、try、catch)

要求: 1.index<0抛出异常eNegative。

             2.index=0抛出异常eZero。

             3.index>1000 抛出异常eTooBig。

             4.index<10抛出异常eTooSmall。

             5.eSize类是以上类的父类实现有参数构造,并定义virtual void printErr ( )输出错误。

#include<iostream>
using namespace std;
class 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
		{
			protected:
				const char *ErrMsg;
			public:
				eSize(char *msg):ErrMsg(msg)
				{
					
				}
				virtual void printErr()=0;
		};
		class eNegative:public eSize
		{
			public:
				eNegative():eSize("Negative Exception")
				{
					
				}
				void printErr()
				{
					cout<<ErrMsg<<endl;
				}
		};
		class eZero:public eSize
		{
			public:
				eZero():eSize("Zero Expection")
				{
					
				}
				void printErr()
				{
					cout<<ErrMsg<<endl;
				}
		}; 
		class eTooBig:public eSize
		{
			public:
				eTooBig():eSize("TooBig Expection")
				{
					
				}
				void printErr()
				{
					cout<<ErrMsg<<endl;
				}
		};
		class eTooSmall:public eSize
		{
			public:
				eTooSmall():eSize("TooSmall Expection")
				{
					
				}
				void printErr()
				{
					cout<<ErrMsg<<endl;
				}
		};
};
MyArray::MyArray(int l)
{
	m_len=l;
	if(m_len<0)
	{
		throw eNegative();
	}
	if(m_len==0)
	{
		throw eZero();
	}
	if(m_len>1000)
	{
		throw eTooBig();
	}
	if(m_len>0&&m_len<10)
	{
		throw eTooSmall();
	}
}
MyArray::~MyArray()
{
	if(m_data!=NULL)
	{
		delete []m_data;
	}
}
int main()
{
	try
	{
		MyArray a(9);  //打印 TooSmall Expection
		//如果为 a(0),打印 Zero Expection
		//如果为 a(-1),打印 Negative Exception
		//如果为 a(1001),打印 TooBig Expection
		for(int i=0;i<a.GetLength();i++)
		{
			a[i]=i;
		}
	}
	catch(MyArray::eNegative &e)
	{
		e.printErr();
	}
	catch(MyArray::eZero &e)
	{
		e.printErr();
	}
	catch(MyArray::eTooBig &e)
	{
		e.printErr();
	}
	catch(MyArray::eTooSmall &e)
	{
		e.printErr();
	}
	return 0;
}

运行结果:

 

猜你喜欢

转载自blog.csdn.net/mmmmmmyy/article/details/81407283