?? 例14.3.txt
字號:
例14.3 在異常處理中處理析構函數。
這是一個為說明在異常處理中調用析構函數的示例,為了清晰地表示流程,程序中加入了一些cout語句,輸出有關的信息,以便讀者對照結果分析程序。
#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) throw num; //如num=0,拋出int型變量num
else cout<<num<<″ ″<<name<<endl; //若num≠0,輸出num,name
cout<<″in get_data()″<<endl; //輸出信息,表示目前在get_data函數中
}
void fun( )
{Student stud1(1101,″Tan″); //建立對象stud1
stud1.get_data( ); //調用stud1的get_data函數
Student stud2(0,″Li″); //建立對象stud2
stud2.get_data( ); //調用stud2的get_data函數
}
int main( )
{cout<<″main begin″<<endl; //表示主函數開始了
cout<<″call fun( )″<<endl; //表示調用fun函數
try
{fun( );} //調用fun函數
catch(int n)
{cout<<″num=″<<n<<″,error!″<<endl;} //表示num=0出錯
cout<<″main end″<<endl; //表示主函數結束
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -