C++标准库 Utilities library typeinfo

来源:互联网 发布:观测数据 英文 编辑:程序博客网 时间:2024/05/21 04:40

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

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

typeinfo

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

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


先来介绍type_info要讲type_info不得不先来说说操作符typeid。它用于获得valuetype的类型,它的使用方法与sizeof类似,都是作用于valuetypesizeof的结果为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的顺序 (这个顺序应该是规定好的,但是没找到,标准上写的是 implementations 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

原创粉丝点击