#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;
}
c++异常的一些心得
最新推荐文章于 2023-05-24 21:58:39 发布