您的位置:首页 > 其它

在异常处理中处理析构函数

2016-05-29 13:43 351 查看
例1:在异常处理中处理析构函数。
程序:
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(int n, string nam)//定义构造函数
{
cout << "constructor-" << n << endl;
num = n;
name = nam;
}
~Student()//定义析构函数
{
cout << "destructor-" << num << endl;
}
void get_data();
private:
int num;
string name;
};

void Student::get_data()
{
if (num == 0)//如果num=0,抛出int型变量num
{
throw num;
}
else//如果num不等于0,输出num,name
{
cout << num << " " << name << endl;
}
cout << "in get_data()" << endl;
}

void fun()
{
Student stud1(1101, "tan");
stud1.get_data();
Student stud2(0, "li");
stud2.get_data();
}

int main()
{
cout << "main begin" << endl;//表示主函数开始了
cout << "call fun()" << endl;//调用fun()函数
try
{
fun();
}
catch (int n)
{
cout << "num=" << n << ",error!" << endl;//num=0出错
}
cout << "main end" << endl;//表示主函数结束
system("pause");
return 0;
}
程序分析:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M02/7F/03/wKioL1cQVmzgR8I4AACY2e551-c276.png" title="图片1.png" alt="wKioL1cQVmzgR8I4AACY2e551-c276.png" />650) this.width=650;" src="http://s5.51cto.com/wyfs02/M00/7F/06/wKiom1cQVcfjRbalAAODqxKXdKo103.png" title="图片2.png" alt="wKiom1cQVcfjRbalAAODqxKXdKo103.png" />
main begin
call fun()
constructor-1101
1101 tan
in get_data()
constructor-0
destructor-0
destructor-1101
num=0,error!
main end
请按任意键继续. . .
例2:在上题的基础上进行变形,分析执行过程,由于异常处理调用了哪些析构函数。
程序:
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(int n, string nam)//定义构造函数
{
cout << "constructor-" << n << endl;
num = n;
name = nam;
}
~Student()//定义析构函数
{
cout << "destructor-" << num << endl;
}
void get_data();
private:
int num;
string name;
};

void Student::get_data()
{
if (num == 0)//如果num=0,抛出int型变量num
{
throw num;
}
else//如果num不等于0,输出num,name
{
cout << num << " " << name << endl;
}
cout << "in get_data()" << endl;
}

void fun()
{
Student stud1(1101, "tan");
stud1.get_data();
try
{
Student stud2(0, "li");
stud2.get_data();
}
catch (int n)
{
cout << "num=" << n << ",error!" << endl;//num=0出错
}
}

int main()
{
cout << "main begin" << endl;//表示主函数开始了
cout << "call fun()" << endl;//调用fun()函数
fun();
cout << "main end" << endl;//表示主函数结束
system("pause");
return 0;
}

程序分析:和上题的不同之处在与,本题在输出“destructor-0”后,再执行catch语句,输出“num=0,error!”,fun函数执行完毕,在流程转回main函数之前先调用stud1的析构函数,输出“destructor-1101”,最后执行main函数中最后一行cout语句,输出“main end”。
运行结果:
main begin
call fun()
constructor-1101
1101 tan
in get_data()
constructor-0
destructor-0
num=0,error!
destructor-1101
main end
请按任意键继续. . .

本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1764068
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: