为什么基类catch块捕获派生类对象? [英] Why Base Class catch block catch derived class object?
问题描述
为什么 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 parametersT
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
andT
are the same type (ignoring top-level cv-qualifiers onT
)T
is an lvalue-reference to (possibly cv-qualified)E
T
is an unambiguous public base class ofE
- […]
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块捕获派生类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!