继承在异常中的应用
异常是类 -创建自己的一个异常类
异常派生
异常中的数据,数据成员
按引用传递异常
--在异常中使用虚函数
案例:设计一个数组类,重载【】操作
数组初始化时,对数组的个数进行有效性检查。
1)index < 0 抛出异常eNegative
2) index = 0 抛出异常eZero
3) index > 1000 抛出异常eTooBig
4) index < 3 抛出异常eTooSmall
5) eSize类是以上类的父类,实现有参构造,并定义virtual void printErr()输出错误
#include<iostream> using namespace std; 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 << endl; } protected: int m_size; }; class eNegative : public eSize { public: eNegative(int size) : eSize(size) { } virtual void printErr() { cout << "eNegative类 size:" << m_size << endl; } }; class eZero : public eSize { public: eZero(int size) : eSize(size) { } virtual void printErr() { cout << "eZero类 size:" << m_size << endl; } }; class eTooBig : public eSize { public: eTooBig(int size) : eSize(size) { } virtual void printErr() { cout << "eTooBig类 size:" << m_size << endl; } }; class eTooSmall : public eSize { public: eTooSmall(int size) : eSize(size) { } virtual void printErr() { cout << "eTooSmall类 size:" << m_size << endl; } }; 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; } int main()//做优化 { try { MyArray a1(-5); for (int i = 0; i < a1.getLen(); i++) { a1[i] = i + 1; cout << a1[i] << " "; } } catch (MyArray::eSize &e) { e.printErr(); } catch (...) { } cout << endl; system("pause"); return 0; }