资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

例1:在异常处理中处理析构函数。

企业建站必须是能够以充分展现企业形象为主要目的,是企业文化与产品对外扩展宣传的重要窗口,一个合格的网站不仅仅能为公司带来巨大的互联网上的收集和信息发布平台,成都创新互联面向各种领域:成都塔吊租赁成都网站设计网络营销推广解决方案、网站设计等建站排名服务。


程序:

#include

#include

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

#include

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://cdkjz.cn/article/iehoep.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220