11实例数组异常的检测_判断数组的个数_类中包含类


#include <iostream>
using namespace std;
/*
案例:设计一个数组类 MyArray,重载[]操作,
数组初始化时,对数组的个数进行有效检查
1)	index<0 抛出异常eNegative
2)	index = 0 抛出异常 eZero
3)index>1000抛出异常eTooBig
4)index<10 抛出异常eTooSmall
5)eSize类是以上类的父类,实现有参数构造、并定义virtual void printErr()输出错误。


*/

class MyArray//类中包含子类
{
public:
	MyArray(int len);
	~MyArray();
public:
	int & operator[](int index);
	int getLen();

	class eSize
	{
	public:
		eSize(int size)
		{
			m_size = size;
		}
		virtual void printErr()
		{
			cout << "size:" << m_size << " ";
		}
	protected:
		int m_size;
	};
	class eNegative : public eSize
	{
	public:
		eNegative(int size) : eSize(size)
		{
			;
		}
		virtual void printErr()
		{
			cout << "eNegative 类型 size:" << m_size << " ";
		}
	};
	class eZero : public eSize
	{
	public:
		eZero(int size) : eSize(size)
		{
			;
		}
		virtual void printErr()
		{
			cout << "eZero 类型 size:" << m_size << " ";
		}
	};
	class eTooBig : public eSize
	{
	public:
		eTooBig(int size) : eSize(size)
		{
			;
		}
		virtual void printErr()
		{
			cout << "eTooBig 类型 size:" << m_size << " ";
		}
	};
	class eTooSmall : public eSize
	{
	public:
		eTooSmall(int size) : eSize(size)
		{
			;
		}
		virtual void printErr()
		{
			cout << "eTooSmall 类型 size:" << m_size << " ";
		}
	};

private:
	int *m_space;
	int m_len;
};


MyArray::MyArray(int len)
{
	if (len  < 0)
	{
		throw eNegative(len);
	}
	else if (len == 0)
	{
		throw eZero(len);
	}
	else if (len > 1000)
	{
		throw eTooBig(len);
	}
	else if (len < 3)
	{
		throw eTooSmall(len);
	}
	m_len = len;
	m_space = new int[len];
}

MyArray::~MyArray()
{
	if (m_space != NULL)
	{
		delete[] m_space;
		m_space = NULL;
		m_len = 0;
	}
}

int & MyArray::operator[](int index)
{
	return m_space[index];
}

int MyArray::getLen()
{
	return m_len;
}



// 不推荐,父类的异常list出来
void main()
{

	try
	{
		MyArray a(-5);
		for (int i = 0; i<a.getLen(); i++)
		{
			a[i] = i + 1;
			printf("%d ", a[i]);
		}
	}
	catch (MyArray::eNegative e)
	{
		cout << "eNegative 类型异常" << endl;
	}
	catch (MyArray::eZero e)
	{
		cout << "eZero 类型异常" << endl;
	}
	catch (MyArray::eTooBig e)
	{
		cout << "eTooBig 类型异常" << endl;
	}
	catch (MyArray::eTooSmall e)
	{
		cout << "eTooSmall 类型异常" << endl;
	}

	catch (...)
	{
		cout << "未知类型的异常" << endl;
	}


	cout << "hello..." << endl;
	system("pause");
	return;
}
/*

---------------------------------------------
eNegative 类型异常
hello...
请按任意键继续. . .


---------------------------------------------
*/

猜你喜欢

转载自blog.csdn.net/baixiaolong1993/article/details/89501592