从std :: exception类和typeid继承

Fro*_*art 3 c++

为什么std :: exception类的继承为以下代码片段提供了不同的输出:

#include <iostream>
#include <typeinfo>

class Base {};
class Derived: public Base {};

int main()
{
  try
  {
    throw Derived();
  }
  catch (const Base& ex)
  {
    std::cout << typeid(ex).name() << '\n';
  }
}
Run Code Online (Sandbox Code Playgroud)

产量

班级基地

#include <exception>
#include <iostream>
#include <typeinfo>

class Base : public std::exception {};
class Derived: public Base {};

int main()
{
  try
  {
    throw Derived();
  }
  catch (const Base& ex)
  {
    std::cout << typeid(ex).name() << '\n';
  }
}
Run Code Online (Sandbox Code Playgroud)

产量

class Derived

NPE*_*NPE 5

如果它声明或继承至少一个虚函数,我们称它为类多态.

typeid()对于多态和非多态类的行为有所不同:https://stackoverflow.com/a/11484105/367273

继承std::exception使您的类具有多态性(因为std::exception它具有虚拟析构函数和虚拟成员函数).

这解释了两个测试之间的行为差​​异.