C ++中的异常处理和对象销毁
C++中的析构函数基本上是在对象被销毁并从系统释放内存时调用的。当在类中引发异常时,在执行catch块之前会自动调用析构函数。
算法
Begin
Declare a class sample1.
Declare a constructor of sample1.
Print “Construct an Object of sample1”
Declare a destructor of sample1.
Print “Destruct an Object of sample1”
Declare a class sample.
Declare a constructor of sample2.
Declare variable i of the integer datatype.
Initialize i = 7.
Print “Construct an Object of sample1”.
Throw i.
Declare a destructor of sample2.
Print “Destruct an Object of sample2”
Try:
Declare an object s1 of class sample1.
Declare an object s2 of class sample2.
Ctach(int i)
Print “Caught”.
Print the value of variable i.
End.范例程式码
#include <iostream>
using namespace std;
class Sample1 {
public:
Sample1() {
cout << "Construct an Object of sample1" << endl;
}
~Sample1() {
cout << "Destruct an Object of sample1" << endl;
}
};
class Sample2 {
public:
Sample2() {
int i =7;
cout << "Construct an Object of sample2" << endl;
throw i;
}
~Sample2() {
cout << "Destruct an Object of sample2" << endl;
}
};
int main() {
try {
Sample1 s1;
Sample2 s2;
} catch(int i) {
cout << "Caught " << i << endl;
}
}输出结果
Construct an Object of sample1 Construct an Object of sample2 Destruct an Object of sample1 Caught 7
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下