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

例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;

}

程序分析:

wKioL1cQVmzgR8I4AACY2e551-c276.pngwKiom1cQVcfjRbalAAODqxKXdKo103.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值