我先从Except里派生了Except1和Except2:
C/C++ code #ifndef EXCEPT_H#define EXCEPT_H
class Except{public: Except(){} virtual
~Except(){} virtual
const
char* what() const{ return
"Ex!"; }};class Except1: public Except{public: Except1(){} virtual
~Except1(){} virtual
const
char* what() const{ return
"Ex1!"; }};class Except2: public Except{public: Except2(){} virtual
~Except2(){} virtual
const
char* what() const{ return
"Ex2!"; }};#endif
然后thro类抛出异常:
C/C++ code #ifndef THRO_H#define THRO_H#include "Except.h"#include <iostream>
using std::cout;class Thro{public: Thro(int a){ if(a==1) throw
&Except1(); else
if(a==2) throw
&Except2(); cout<<"Fine.\n"; } virtual
~Thro(){}private: int a;};#endif
主函数:
C/C++ code #include <iostream>#include "Except.h"#include "thro.h"
using
namespace std;int main(){ int a; try{ while(cin>>a){ Thro exp(a); } }catch(Except *ex){ cout<<ex->what()<<endl; }}
我自己臆想我分别把Except1、Except2的地址throw给了Except *ex,又因为what()是个virtual函数,所以他们应该分别调用Except1的what()和Except2的what(),但是经测试无论输入1或2,输出都是"Ex!"即基类的what(),请问哪里错了?应该怎么对异常处理实现多态?
多谢指教! |