异常的层次结构(继承在异常中的应用)

案例:设计一个数组类 MyArray,重载[]操作,

数组初始化时,对数组的个数进行有效检查

1)size<0 抛出异常eNegative  

2)size= 0 抛出异常 eZero  

3)size>1000抛出异常eTooBig 

4)size<10 抛出异常eTooSmall

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

#pragma warning(disable : 4996)
#include <iostream>
using namespace std;

class eSize
{
public:
	eSize(int size)
	{
		this->m_size = size;
	}
	virtual void PrintErr() = 0;
protected:
	int m_size;
};
class eNegative :public eSize
{
public:
	eNegative(int size) :eSize(size)
	{
		;
	}

	virtual void PrintErr()
	{
		printf("抛出异常eNegative,size:%d", m_size);
	}
};
class eZero :public eSize
{
public:
	eZero(int size) :eSize(size)
	{
		;
	}
	virtual void PrintErr()
	{
		printf("抛出异常eZero,size:%d", m_size);
	}
};
class eTooBig :public eSize
{
public:
	eTooBig(int size) :eSize(size)
	{
		;
	}
	virtual void PrintErr()
	{
		printf("抛出异常eTooBig,size:%d", m_size);
	}
};
class eTooSmall :public eSize
{
public:
	eTooSmall(int size) :eSize(size)
	{
		;
	}
	virtual void PrintErr()
	{
		printf("抛出异常eTooSmall,size:%d", m_size);
	}
};

class MyArray
{
public:
	MyArray(int len);
	int & operator[](int index);
	~MyArray();
	int GetLen();
private:
	int *m_place;
	int m_len;
};

MyArray::MyArray(int len)
{
	if (len < 0)
	{
		throw eNegative(len);
	}
	else if(len == 0)
	{
		throw eZero(len);
	}
	else if (len >100)
	{
		throw eTooBig(len);
	}
	else if (len < 3)
	{
		throw eTooSmall(len);
	}

	m_len = len;
	m_place = new int[len];
}
MyArray::~MyArray()
{
	if (m_place != NULL)
	{
		delete[] m_place;
		m_place = NULL;
		m_len = 0;
	}
}

int & MyArray::operator[](int index)
{
	return m_place[index];
}
int MyArray::GetLen()
{
	return m_len;
}


int main()
{
	try
	{
		MyArray a(120);
		for (int i = 0; i < a.GetLen(); i++)
		{
			a[i] = i + 1;
			printf("%d ", a[i]);
		}
	}
	catch (eSize &e)
	{
		e.PrintErr();
	}
	
	system("pause");
	return 0;
}

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值