溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

在異常處理中處理析構(gòu)函數(shù)

發(fā)布時間:2020-07-25 02:41:39 來源:網(wǎng)絡(luò) 閱讀:392 作者:巖梟 欄目:編程語言

例1:在異常處理中處理析構(gòu)函數(shù)。

程序:

#include<iostream>

#include<string>

using namespace std;

class Student

{

public:

Student(int n, string nam)//定義構(gòu)造函數(shù)

{

cout << "constructor-" << n << endl;

num = n;

name = nam;

}

~Student()//定義析構(gòu)函數(shù)

{

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;//表示主函數(shù)開始了

cout << "call fun()" << endl;//調(diào)用fun()函數(shù)

try

{

fun();

}

catch (int n)

{

cout << "num=" << n << ",error!" << endl;//num=0出錯

}

cout << "main end" << endl;//表示主函數(shù)結(jié)束

system("pause");

return 0;

}

程序分析:

在異常處理中處理析構(gòu)函數(shù)在異常處理中處理析構(gòu)函數(shù)

main begin

call fun()

constructor-1101

1101 tan

in get_data()

constructor-0

destructor-0

destructor-1101

num=0,error!

main end

請按任意鍵繼續(xù). . .

例2:在上題的基礎(chǔ)上進行變形,分析執(zhí)行過程,由于異常處理調(diào)用了哪些析構(gòu)函數(shù)。

程序:

#include<iostream>

#include<string>

using namespace std;

class Student

{

public:

Student(int n, string nam)//定義構(gòu)造函數(shù)

{

cout << "constructor-" << n << endl;

num = n;

name = nam;

}

~Student()//定義析構(gòu)函數(shù)

{

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;//表示主函數(shù)開始了

cout << "call fun()" << endl;//調(diào)用fun()函數(shù)

fun();

cout << "main end" << endl;//表示主函數(shù)結(jié)束

system("pause");

return 0;

}

程序分析:和上題的不同之處在與,本題在輸出“destructor-0”后,再執(zhí)行catch語句,輸出“num=0,error!”,fun函數(shù)執(zhí)行完畢,在流程轉(zhuǎn)回main函數(shù)之前先調(diào)用stud1的析構(gòu)函數(shù),輸出“destructor-1101”,最后執(zhí)行main函數(shù)中最后一行cout語句,輸出“main end”。

運行結(jié)果:

main begin

call fun()

constructor-1101

1101 tan

in get_data()

constructor-0

destructor-0

num=0,error!

destructor-1101

main end

請按任意鍵繼續(xù). . .


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI