c – 在多态对象上使用typeid时,是否必须定义它?

c – 在多态对象上使用typeid时,是否必须定义它?,第1张

概述在多态对象上使用typeid时,我认为必须定义对象(而不仅仅是声明),因为typeid *** 作需要在运行时获取对象的信息.这是我的代码: #include <iostream>#include <typeinfo>class D { virtual ~D() {}};extern D d;int main(){ std::cout << typeid(d).name() 在多态对象上使用typeID时,我认为必须定义对象(而不仅仅是声明),因为typeID *** 作需要在运行时获取对象的信息.这是我的代码:
#include <iostream>#include <typeinfo>class D {    virtual ~D() {}};extern D d;int main(){    std::cout << typeID(d).name() << std::endl;    std::cout << sizeof(d) << std::endl;}

使用clang 3.4,我收到链接错误:

undefined reference to `d’

但是在g++ 4.8.1,它运作良好,我得到了结果:

1D
8

我的问题:

>哪一个是对的?
> g如何实现typeID?如何在没有定义的情况下从多态对象中获取信息?

解决方法 从 http://en.cppreference.com/w/cpp/language/typeid起

a) If Expression is a glvalue Expression that IDentifIEs an object of a polymorphic type (that is,a class that declares or inherits at least one virtual function),the typeID Expression evaluates the Expression and then refers to the std::type_info object that represents the dynamic type of the Expression. If the result of the evaluated Expression is a null pointer,an exception of type std::bad_typeID or a type derived from std::bad_typeID is thrown.

听起来像clang 3.4是对的.

更新

标准说:

When typeID is applIEd to a glvalue Expression whose type is a polymorphic class type (10.3),the result refers to a std::type_info object representing the type of the most derived object (1.8) (that is,the dynamic type) to which the glvalue refers. If the glvalue Expression is obtained by applying the unary * operator to a pointer and the pointer is a null pointer value (4.10),the typeID Expression throws the std::bad_typeID
exception (18.7.3).

它与cppreference.com使用的语言略有不同,但仍然指出clang 3.4是正确的.

总结

以上是内存溢出为你收集整理的c – 在多态对象上使用typeid时,是否必须定义它?全部内容,希望文章能够帮你解决c – 在多态对象上使用typeid时,是否必须定义它?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1240044.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存