[C++]用多态实现简单异常处理

案例说明

设计一个数组类MyArray,重载[]符号操作,
数组初始化时,对数组的个数进行有效检查
1)index<0 抛出异常eNegtive
2)index=0 抛出异常eZero
3)index>1000 抛出异常eTooBig
4)index<10 抛出异常eTooSmall
4)eSize 类是上述类的基类,实现有参构造,定义virtual void printErr()输出错误

程序设计

eSize.hpp
#pragma once
#define  _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;

class eSize
{
public:
	virtual void printErr() = 0;
};

class eNegtive: public eSize
{
public:
	eNegtive(int index)
	{
		mIndex = index;
	}
public:
	void printErr()
	{
		cout << "eNegtive:" ;
		cout << mIndex << endl;
	}
private:
	int mIndex;
};

class eZero: public eSize
{
public:
	eZero(int index)
	{
		mIndex = index;
	}
public:
	void printErr()
	{
		cout << "eZero: " ;
		cout << mIndex << endl;
	}
private:
	int mIndex;
};

class eTooBig : public eSize
{
public:
	eTooBig(int index)
	{
		mIndex = index;
	}
public:
	void printErr()
	{
		cout << "eTooBig: " ;
		cout << mIndex << endl;
	}
private:
	int mIndex;
};

class eTooSmall : public eSize
{
public:
	eTooSmall(int index)
	{
		mIndex = index;
	}
public:
	void printErr()
	{
		cout << "eTooSmall: " ;
		cout << mIndex << endl;
	}
private:
	int mIndex;
};
MyArray.hpp
#pragma once
#define  _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include "eSize.hpp"

class MyArray
{
public:
	MyArray();
	MyArray(int num);
	~MyArray();

public:
	//重载[]
	int& operator[](int index);

private:

	int mLen;
	int* mBuf;
};

MyArray::MyArray()
{
	mLen = 0;
	mBuf = NULL;
	throw eZero(mLen);
}

MyArray::MyArray(int num)
{
	mLen = num;
	if (mLen < 0)
	{
		throw eNegtive(mLen);
	}
	if (mLen > 1000)
	{
		throw eTooBig(mLen);
	}
	if (0 < mLen < 10)
	{
		throw eTooSmall(mLen);
	}

	mBuf = new int[mLen];
}

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

int& MyArray::operator [](int index)
{
	return mBuf[index];
}
main.cpp
#include <iostream>
#include "eSize.hpp"
#include "MyArray.hpp"
using namespace std;

void playFunc()
{
	try
	{
		MyArray m(100000);
	}
	catch (eSize &e)	//用基类接实现多态
	{
		e.printErr();
	}
	catch ( ... )
	{
		cout << "其他错误" << endl;
	}
	

}


int main()
{
	playFunc();
	

	cout << "hello world!" << endl;
	system("pause");
	return 0;
}

结论

异常处理机制比传统的错误检查方便,利用多态和异常结合,能够大大的简化代码,该文供以后复习使用
多态实现条件:
1 、有继承
2 、有虚函数重写
3 、有基类指针指向派生类对象
这样在基类指针调用重写的函数时,就会发生多态

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值