如何在C ++中找出指针指向的对象的类型? [英] How to find out what type of object a pointer points to in C++?

查看:223
本文介绍了如何在C ++中找出指针指向的对象的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 class SuperClass {public:int a; } class SubClass:SuperClass {public:int b; } ,并且我指向SubClass SubClass * subPointer 的一个实例,并指向一个SuperClass指针 SuperClass * superPointer = subPointer 。当然,我总是可以把 superPointer 对象转换为SubClass的指针,因为它只存储一个地址。但是我怎么知道对象 superPointer 是指向一个SubClass的实例还是只是一个SuperClass指针?

Let's say I have class SuperClass { public: int a; } and class SubClass : SuperClass { public: int b; } and I took a pointer to an instance of the SubClass SubClass *subPointer and addressed that pointer to a SuperClass pointer SuperClass *superPointer = subPointer. Now of course I can always cast the superPointer object to a pointer of SubClass because the only thing it stores is an adress. But how would I know if the object superPointer is pointing to an instance of SubClass or is just a SuperClass pointer?

推荐答案

您通常不要为此使用 typeid

您通常要使用 dynamic_cast

if (SubClass *p = dynamic_cast<SubClass *>(SuperClassPtr))
    // If we get here (the `if` succeeds) it was pointing to an object of 
    // the derived class and `p` is now pointing at that derived object.

首先,你需要在基类中至少有一个虚函数,这样才能工作(但是如果没有虚函数,为什么要继承它呢?)

A couple of notes though. First of all, you need at least one virtual function in the base class for this to work (but if it doesn't have a virtual function, why are you inheriting from it?)

第二,希望这往往表示代码的设计问题。在大多数情况下,你想在基类中定义一个虚函数,你必须在派生类中重写它来做任何需要,所以你可以使用指向基类的指针。

Second, wanting this very often tends to indicate design problems with the code. In most cases, you want to define a virtual function in the base class, which you (if necessary) override in the derived class to do whatever's needed so you can just use a pointer to the base class throughout.

最后,因为它现在,大多数转换将失败 - 你使用默认(私有)继承,它阻止隐式转换 derived * 到到你通常预期会发生的基本* (你可能想要 class SubClass:public SuperClass )。

Finally, as it stands right now, most of the conversions will fail -- you've used the default (private) inheritance, which prevents the implicit conversion from derived * to base * that you'd normally expect to see happen (you probably want class SubClass : public SuperClass).

这篇关于如何在C ++中找出指针指向的对象的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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