📜  C ++ |异常处理问题9

📅  最后修改于: 2021-06-30 00:21:01             🧑  作者: Mango

#include 
using namespace std;
  
class Test {
  static int count;
  int id;
public:
  Test() {
    count++;
    id = count;
    cout << "Constructing object number " << id << endl;
    if(id == 4)
       throw 4;
  }
  ~Test() { cout << "Destructing object number " << id << endl; }
};
  
int Test::count = 0;
  
int main() {
  try {
    Test array[5];
  } catch(int i) {
    cout << "Caught " << i << endl;
  }
}

(一种)

Constructing object number 1
Constructing object number 2
Constructing object number 3
Constructing object number 4
Destructing object number 1
Destructing object number 2
Destructing object number 3
Destructing object number 4
Caught 4

(B)

Constructing object number 1
Constructing object number 2
Constructing object number 3
Constructing object number 4
Destructing object number 3
Destructing object number 2
Destructing object number 1
Caught 4

(C)

Constructing object number 1
Constructing object number 2
Constructing object number 3
Constructing object number 4
Destructing object number 4
Destructing object number 3
Destructing object number 2
Destructing object number 1
Caught 4

(D)

Constructing object number 1
Constructing object number 2
Constructing object number 3
Constructing object number 4
Destructing object number 1
Destructing object number 2
Destructing object number 3
Caught 4

答案: (B)
说明:析构函数以与构造函数相反的顺序调用。同样,在try块之后,仅针对完全构造的对象调用析构函数。
这个问题的测验

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。