| 定义于头文件 |
std::bad_typeid
| class bad_typeid : public std::exception; |
此类型的异常在应用 typeid 运算符到多态类型的空指针值时抛出。
![]()
| (构造函数) | 构造新的 bad_typeid 对象(公开成员函数) |
| (析构函数) [虚] | 析构该异常对象 ( std::exception 的虚公开成员函数) |
| what [虚] | 返回解释性字符串 ( std::exception 的虚公开成员函数) |
- #include <iostream>
- #include <typeinfo>
-
- struct S // 类型必须是多态
- {
- S() {}
-
- virtual void f() {}
- };
-
- int main()
- {
- S* p = nullptr;
- try
- {
- std::cout << typeid(*p).name() << std::endl;
- }
- catch (const std::bad_typeid& e)
- {
- std::cout << e.what() << std::endl;
- }
-
- S* p1 = new S;
- try
- {
- std::cout << typeid(*p1).name() << std::endl;
- }
- catch (const std::bad_typeid& e)
- {
- std::cout << e.what() << std::endl;
- }
-
- return 0;
- }

std::bad_cast
| class bad_cast : public std::exception; |
![]()
继承图
| (构造函数) | 构造新的 bad_cast 对象 (公开成员函数) |
| (析构函数) [虚] | 析构该异常对象 ( std::exception 的虚公开成员函数) |
| what [虚] | 返回解释性字符串 ( std::exception 的虚公开成员函数) |
- #include <iostream>
- #include <typeinfo>
-
- struct Foo
- {
- virtual ~Foo() {}
- };
-
- struct Bar
- {
- virtual ~Bar() {}
- };
-
- int main()
- {
- Bar b;
- try
- {
- Foo& f = dynamic_cast<Foo&>(b);
- }
- catch (const std::bad_cast& e)
- {
- std::cout << e.what() << std::endl;
- }
-
- return 0;
- }
