为什么 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 $在处理程序-seq 中的每个 catch子句的c $ c>,按照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块捕获派生类对象?
发布评论