C++标准模板(STL)- 类型支持 (运行时类型识别,bad_typeid,bad_cast )

运行时类型识别

定义于头文件 <typeinfo>

当 typeid 表达式中的实参为空值时抛出的异常

std::bad_typeid

class bad_typeid : public std::exception;

 此类型的异常在应用 typeid 运算符到多态类型的空指针值时抛出。

成员函数

(构造函数)

构造新的 bad_typeid 对象
(公开成员函数)

继承自 std::exception

成员函数

(析构函数)

[虚]

析构该异常对象
(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;
}

输出

由非法的 dynamic_cast 表达式抛出的异常,即引用类型转型失败

std::bad_cast

class bad_cast : public std::exception;

 

继承图

成员函数

(构造函数)

构造新的 bad_cast 对象
(公开成员函数)

继承自 std::exception

成员函数

(析构函数)

[虚]

析构该异常对象
(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;
}

输出

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值