c – 当我抛出派生类的对象时,为什么捕获基类的块正在捕获异常?

前端之家收集整理的这篇文章主要介绍了c – 当我抛出派生类的对象时,为什么捕获基类的块正在捕获异常?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Why Base Class catch block catch derived class object?3个
> Why throw at derived class catches by base?5个
如果我传递派生类的对象,则应调用派生类catch块.但输出表明异常是由基类捕获的.为什么?
#include<iostream>
using namespace std;

class Base {};
class Derived: public Base {};
int main()
{
   Derived d;
   // some other stuff
   try {
       // Some monitored code
       throw d;
   }
   catch(Base b) { 
        cout<<"Caught Base Exception";
   }
   catch(Derived d) {  //This catch block is NEVER executed
        cout<<"Caught Derived Exception";
   }
   getchar();
   return 0;
}

解决方法

该标准以(见 [except.handle]/4)工作草案为例,强调我的):

The handlers for a try block are tried in order of appearance. [Note:This makes it possible to write handlers that can never be executed,for example by placing a handler for a final derived class after a handler for a corresponding unambiguous public base class.

这正是您在代码中所做的.
因此,无论您的期望是什么,我都会说这是预期的行为.

请注意,您可以交换两个处理程序来解决问题.

原文链接:https://www.f2er.com/c/116675.html

猜你在找的C&C++相关文章