类型不正常工作 [英] Typeid not functioning correcly

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

问题描述

我无法正确获取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类

Class B Class A Class A

我对我的项目使用VS2010

I am using VS2010 for my project

推荐答案

它指向的对象必须是多态的,这样才能正常工作。如果 A virtual 方法比你的代码会按预期工作,例如添加一个虚析构函数, a href =http://rextester.com/PPI9073 =nofollow>演示使用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.

href =http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf =nofollow> C ++草稿标准部分 5.2.8 段落 说:

Quote form the C++ draft standard section 5.2.8 Type identification paragraph 2 says:


当将typeid应用于类型为
多态类类型(10.3)的glvalue表达式时,结果引用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:


应用于除
多态类类型的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 / p>

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.

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

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