Typeid无法正常运作 [英] Typeid not functioning correctly

查看:106
本文介绍了Typeid无法正常运作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法正确获取typeid函数. 我错过了什么吗?

I cannot get typeid function correctly. Am I missing something

代码:

class A
{
     public:
     int a1;
     A()
    {
    }
};


class B: public A
{
    public:
    int b1;
    B()
    {
    }
};


int main()
{
     B tempb;
     A tempa;
     A * ptempa;
     ptempa = &tempb;

     std::cout << typeid(tempb).name() << std::endl;
     std::cout << typeid(tempa).name() << std::endl;
     std::cout << typeid(*ptempa).name() << std::endl;

     return 0;
}

它总是打印:

B级 A级 A级

我正在为项目使用VS2010

I am using VS2010 for my project

推荐答案

它指向的对象必须是多态的,这样才能按预期工作.如果A具有virtual方法,则您的代码将按预期工作,例如添加一个虚拟析构函数,我 demo live在这里使用gcc .

The object it points to must be polymorphic for this to work as you expect. If A had virtual methods than your code would have work as expected, for example adding a virtual destructor, which I demo live here using gcc.

引用 C ++标准草案部分5.2.8 类型标识段落 2 说:

将typeid应用于类型为a的glvalue表达式时 多态类类型(10.3),结果引用一个std :: type_info 代表最派生对象(1.8)[...]

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) [...]

这适用于我们有virtual方法的情况,在您的情况下您没有多态类型,因此第 3 段适用:

Which applies to the case where we have a virtual method, in your case you do not have a polymorphic type so paragraph 3 applies:

当typeid应用于除a的glvalue以外的表达式时 多态类类型,结果引用一个std :: type_info对象 表示表达式的静态类型

When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers to a std::type_info object representing the static type of the expression

因此您将获得static类型,即A.

So you will get the static type back which is A.

只是更完整的部分10.3 虚拟功能说:

Just to be a little more complete section 10.3 Virtual functions says:

虚拟函数支持动态绑定和面向对象 编程.声明或继承虚拟函数的类是 称为多态类.

Virtual functions support dynamic binding and object-oriented programming. A class that declares or inherits a virtual function is called a polymorphic class.

这篇关于Typeid无法正常运作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆