为什么我需要#include< typeinfo>使用typeid运算符时? [英] Why do I need to #include <typeinfo> when using the typeid operator?
问题描述
typeid
表示C ++ RTTI运算符也是C ++关键字.它返回一个 std::type_info
对象,其中包含(动态)类型特定的信息.
The typeid
represents a C++ RTTI operator being also a C++ keyword. It returns a std::type_info
object that holds (dynamic) type specific information.
据我从各种来源了解到,使用typeid
时必须包含<typeinfo>
,否则程序格式错误.实际上,如果我不包含上述标头,我的gcc5.2编译器甚至不会编译该程序.我不明白为什么要强制使用C ++ 关键字包含标头.我理解为每当我们使用在该标头中声明/定义的某个对象时都要强制标头,但typeid
并非类类型.那么强制执行包含标头<typeinfo>
的原因是什么?
From what I understood from various sources, one MUST include <typeinfo>
when using typeid
, otherwise the program is ill-formed. In fact, my gcc5.2 compiler doesn't even compile the program if I don't include the before-mentioned header. I don't understand why is a header inclusion mandated for the usage of a C++ keyword. I understand mandating a header for whenever we use some object declared/defined in that header, but typeid
is not of a class type. So what is the reason behind this enforcement of including the header <typeinfo>
?
推荐答案
下一段:
typeid表达式是指向对象的左值表达式 具有多态类型const的静态存储持续时间 std :: type_info或从其派生的某种类型.
The typeid expression is lvalue expression which refers to an object with static storage duration, of the polymorphic type const std::type_info or of some type derived from it.
因为它是一个左值表达式,它使用引用初始化来声明std::type_info
的初始化程序. <typeinfo>
包含该对象的定义.
Because it is an lvalue expression, which uses reference initialization to declare an initializer of std::type_info
. <typeinfo>
contains the definition for that object.
这篇关于为什么我需要#include< typeinfo>使用typeid运算符时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!