geeksforgeeks-069-c++中的catch块和类型转换

预测下列程序的输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int ()
{
try
{
throw 'x';
}
catch(int x)
{
cout << " Caught int " << x;
}
catch(...)
{
cout << "Defaule catch block";
}
}

1
Defaule catch block

在上面的程序中,一个字符’x’被抛出,有一个捕捉int类型的catch,但是在catch块中不会发生类型转换。
考虑如下程序,转换构造函数没有被抛出对象调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;

class MyExcept1 {};

class MyExcept2
{
public:


MyExcept2 (const MyExcept1 &e )
{
cout << "Conversion constructor called";
}
};

int ()
{
try
{
MyExcept1 myexp1;
throw myexp1;
}
catch(MyExcept2 e2)
{
cout << "Caught MyExcept2 " << endl;
}
catch(...)
{
cout << " Defaule catch block " << endl;
}
return 0;
}

1
Defaule catch block

但是,如果有catch块捕捉基类时,派生类对象在被抛出时会被转化为基类对象。