异常的多态使用
- 利用多态来实现 printError同一个接口调用
- 抛出不同的错误对象,提示不同错误
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; //异常基类 class BaseException { public: virtual void printError() {} }; class OutofRangeException :public BaseException { public: virtual void printError() { cout << "越界异常" << endl; } }; class NullPointerException :public BaseException { public: virtual void printError() { cout << "空指针异常" << endl; } }; void doWork() { //throw NullPointerException(); //抛出空指针异常 throw OutofRangeException(); //抛出越界异常 } void test01() { try { doWork(); } catch (BaseException& e) //BaseException类和其派生类 { e.printError(); //捕获异常 } } int main() { test01(); system("Pause"); return 0; }
结果: