打印

异常处理问题

[复制链接]
860|2
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
txcy|  楼主 | 2012-5-26 23:18 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
我先从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(),请问哪里错了?应该怎么对异常处理实现多态?
多谢指教!

相关帖子

沙发
yybj| | 2012-5-26 23:34 | 只看该作者
LZ这代码编辑的优点乱

使用特权

评论回复
板凳
火箭球迷| | 2012-5-26 23:43 | 只看该作者
楼主需要再重新编辑一下,不然没法看

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

274

主题

2106

帖子

0

粉丝