案例:設計一個數組類 MyArray,重載[]操作,
數組初始化時,對數組的個數進行有效檢查
1) index<0 拋出異常eNegative
2) index = 0 拋出異常 eZero
3)index>1000拋出異常eTooBig
4)index<10 拋出異常eTooSmall
5)eSize類是以上類的父類,實現有參數構造、並定義virtual void printErr()輸出錯誤。
// exception02.cpp: 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class MyArray {
public:
MyArray(int len);
~MyArray() ;
class eSize {
public:
eSize(int size) {
e_size = size;
}
virtual void printErr()=0;
protected:
int e_size;
};
class eNegative :public eSize {
public:
eNegative(int size) :eSize(size) {
cout << "eNegative構造函數" << endl;
}
void printErr() {
cout << "index<0" << endl;
}
};
class eZero :public eSize {
public:
eZero(int size) :eSize(size) {
cout << "eZero構造函數" << endl;
}
void printErr() {
cout << "index=0" << endl;
}
};
class eTooBig :public eSize {
public:
eTooBig(int size) :eSize(size) {
cout << "eTooBig構造函數" << endl;
}
void printErr() {
cout << "index>1000" << endl;
}
};
class eTooSmall :public eSize {
public:
eTooSmall(int size) :eSize(size) {
cout << "eTooSmall構造函數" << endl;
}
void printErr() {
cout << "index<10" << endl;
}
};
public:
int& operator[](int index) {
return m_arr[index];
}
private:
int m_size;
int *m_arr;
};
MyArray::MyArray(int len)
{
if (len < 0)
throw eNegative(len);
if (len == 0)
throw eZero(len);
if (len > 1000)
throw eTooBig(len);
if (len>0&&len < 10)
throw eTooSmall(len);
m_size = len;
m_arr = new int[m_size];
}
MyArray::~MyArray()
{
if (m_arr != NULL)
{
delete[] m_arr;
m_arr = NULL;
m_arr = 0;
}
}
int main(){
try
{
MyArray test1(1001);
}
//多態
/*
catch (MyArray::eSize &e)
{
e.printErr();
}
*/
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;
}