C++中的catch块和类型转换如何理解?

2021年3月21日16:49:18 发表评论 733 次浏览

本文概述

预测以下C ++程序的输出。

C ++

#include <iostream>
using namespace std;
 
int main()
{
     try
     {
         throw 'x' ;
     }
     catch ( int x)
     {
         cout << " Caught int " << x;
     }
     catch (...)
     {
         cout << "Default catch block" ;
     }
}

输出如下:

Default catch block

在上面的程序中, 抛出了字符" x", 并且有一个catch块来捕获一个int。可能有人认为可以通过考虑ASCII值" x"来匹配int catch块。但是不会对catch块执行此类转换。考虑下面的程序作为另一个示例, 其中不为引发的对象调用转换构造函数。

C ++

#include <iostream>
using namespace std;
 
class MyExcept1 {};
 
class MyExcept2
{
public :
 
     // Conversion constructor
     MyExcept2 ( const MyExcept1 &e )
     {
         cout << "Conversion constructor called" ;
     }
};
 
int main()
{
     try
     {
         MyExcept1 myexp1;
         throw myexp1;
     }
     catch (MyExcept2 e2)
     {
         cout << "Caught MyExcept2 " << endl;
     }
     catch (...)
     {
         cout << " Default catch block " << endl;
     }
     return 0;
}

输出如下:

Default catch block

附带说明一下, 当引发派生对象并且有一个catch块来捕捉基本类型时, 派生类型对象将转换为基本类型。看到

这个GFact

更多细节。

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: