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

发布时间:2020-07-25 02:41:39 作者:岩枭
来源:网络 阅读:383

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

}

程序分析:

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

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

请按任意键继续. . .


推荐阅读:
  1. 异常处理
  2. Java中的异常处理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

程序 include 异常处

上一篇:java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind

下一篇:Parallel ForEach For 多线程并行计算使用注意

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》