C++标准库 Utilities library typeinfo

该系列博文主要参考自 cppreference.com 和 cplusplus.com

由于博主水平有限,内容仅供参考

typeinfo

该头文件下有三个class,分别是type_info, bad_cast 和 bad_typeid。type_info为操作符typeid的返回类型,bad_cast和bad_typeid均为exception类型。

namespace std {
    class type_info;
    class bad_cast;
    class bad_typeid;
}


先来介绍type_info,要讲type_info不得不先来说说操作符typeid。它用于获得value或type的类型,它的使用方法与sizeof类似,都是作用于value或type,sizeof的结果为size_t类型,而typeid的结果就为type_info类型。


class type_info {
public:
    virtual ~type_info();
    bool operator==(const type_info& rhs) const noexcept;
    bool operator!=(const type_info& rhs) const noexcept;
    bool before(const type_info& rhs) const noexcept;
    size_t hash_code() const noexcept;
    const char* name() const noexcept;
    type_info(const type_info& rhs) = delete; // cannot be copied
    type_info& operator=(const type_info& rhs) = delete; // cannot be copied
};



constructor:不允许复制构造

deconstructor:派生对象通过指向基类的指针安全delete

operator=:不允许赋值

operator==/operator!=:判断是否相等

before:判断两个type的顺序 (这个顺序应该是规定好的,但是没找到,标准上写的是 implementation’s collation order

hash_code(c++11):返回类型的hash值

name:返回类型名


其他两个exception较为简单

class bad_cast : public exception {
public:
    bad_cast() noexcept;
    bad_cast(const bad_cast&) noexcept;
    bad_cast& operator=(const bad_cast&) noexcept;
    virtual const char* what() const noexcept;
};



运行无效的dynamic_cast表达式时将throw bad_cast


class bad_cast : public exception {
public:
    bad_cast() noexcept;
    bad_cast(const bad_cast&) noexcept;
    bad_cast& operator=(const bad_cast&) noexcept;
    virtual const char* what() const noexcept;
};



运行无效的typeid表达式时将throw bad_typeid

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值