为什么基类catch块捕获派生类对象?

编程入门 行业动态 更新时间:2024-10-28 02:34:45
本文介绍了为什么基类catch块捕获派生类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么 Base catch handler catch a Derived 对象,如:

Why does the Base catch handler catch a Derived object, as in:

#include <iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; try { throw d; } catch(Base b) { cout << "Caught Base Exception"; } catch(...) { cout << "Default\n"; } return 0; }

我得到的输出是捕获基地异常。我期待着默认。

The output I get is "Caught Base Exception". I was expecting "Default".

推荐答案

Catch子句按照列出的顺序进行评估。当catch子句参数满足与throw表达式相对应的一些前提条件时,搜索可行的catch子句将停止:

Catch clauses are evaluated in the order in which they are listed. A search for a viable catch clause stops when a catch clause parameter satisfies some prerequisite corresponding to the throw expression:

当类型 E 由复合语句中的任何语句抛出,它与形式参数的类型匹配 T ,按照catch子句列出的顺序。如果满足以下条件之一,则为例外:

When an exception of type E is thrown by any statement in compound-statement, it is matched against the types of the formal parameters T of each catch-clause in handler-seq, in the order in which the catch clauses are listed. The exception is a match if any of the following is true:

  • E T 是相同的类型(忽略 T 上的顶级cv限定符)
  • T 是一个左值(可能是cv-qualified)的引用 E
  • T 是一个明确的公共基类 E
  • [...]
  • E and T are the same type (ignoring top-level cv-qualifiers on T)
  • T is an lvalue-reference to (possibly cv-qualified) E
  • T is an unambiguous public base class of E
  • […]

code>是 Derived 的明确基础,因此选择了第一个catch块。由于一个全部处理程序( catch(...))只能出现在catch处理程序列表的最后,它是最不可行的一个catch处理程序的候选人。

Base is an unambiguous base of Derived, so the first catch block is chosen. Since a catch-all handler (catch(...)) can only appear last in the list of catch handlers, it is the least viable candidate for a catch handler.

更多推荐

为什么基类catch块捕获派生类对象?

本文发布于:2023-08-04 13:24:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1296667.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   派生类   catch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!