c++异常的一些心得

#include <iostream>

using namespace std;
class test1
{
public:
    test1()
    {
       cout<<"test1 构造"<<endl;
    }
    ~test1()
    {
        cout<<"test1 析构"<<endl;
    }
};
class test2:public test1
{
    public:
    test2()
    {
        cout<<"test2 构造"<<endl;
    }
    test2(test2 &t)//只能写引用
    {
        cout<<"test2 复制构造"<<endl;
    }
    ~test2()
    {
        cout<<"test2 析构"<<endl;
    }
    void show(){cout<<"I'm  test2"<<endl;}
};
class test0
{
public:
    test0()
    {
        cout<<"test0 构造"<<endl;
    }
    ~test0()
    {
        cout<<"test0 析构"<<endl;
    }
};
class test3:public test0,public test2//先继承谁先构造谁。先构造的后析构
{
    public:
    test3()
    {
        cout<<"test3 构造"<<endl;
    }
    ~test3()
    {
        cout<<"test3 析构"<<endl;
    }
};
void fun()
{
    try
    {
        test2 t;
        throw t;//异常对象直至不用时才析构。抛出异常的值。要调用复制构造函数
    }
    //int a;   try和catch之间不能有其它语句
    catch(test2 &t)//同赋值基类可捕获派生类异常
    {
        cout<<"fun get test1"<<endl;
        throw(t);//若异常为引用抛出原异常而不是副本。t会到被使用完才析构。
    }
}
int main()
{
    //test3  t;
    test2 t2;
    test2 &t=t2;
    try//try 和catch必须成对出现
    {
      fun();
    }
    //catch(...){cout<<"...get test1"<<endl;}语法错误该句只能放最后
    catch(test2 &t1)
    {
        t=t1;
        cout<<"main get test1"<<endl;
    }
    catch(...){cout<<"...get test1"<<endl;}//同case,break语句只执行一条
    t.show();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值