简体   繁体   中英

C++ get type of object

I have a C++ application which has the following classes:

  • class AAA
  • class BBB inherits from AAA
  • class CCC inherits from AAA
  • class DDD inherits from CCC

(All of the classes are marked as public )

Now I have the following map:

map <DWORD, AAA*> 

I find an AAA object in the map , by a DWORD id , but now I want to know what is the type of AAA :

this will be the logic:

if(AAA is BBB)
{
...
}
if(AAA is CCC)
{
...
}
if(AAA is DDD)
{
...
}

Do you know how to write it in C++ (without adding a polymorphic function of getType() )?

Requiring this indicates you are doing it the wrong way. You are trying to replicate something that virtual methods were invented for. Just put a virtual method in your base class.

class AAA
{
public:
    virtual void DoSomething() = 0;
}

class BBB : public AAA
{
public:
    void DoSomething() { ... }
}

class CCC : public AAA
{
public:
    void DoSomething() { ... }
}

class DDD : public AAA
{
public:
    void DoSomething() { ... }
}

And in your calling code, your logic is simple:

// no need for if() blocks. it's the point of virtual methods.
AAA* somePointer;
...
somePointer->DoSomething();

I realize you maybe can't just copy / paste your current "dosomething" code into this. But this is the pattern you should be using for this scenario. Perhaps instead of DoSomething it makes more sense to have something like GetSomeInfo , that the caller can use to do whatever it needs to do. The specific usage of this pattern depends on your context.

If your object is polymorphic (ie has at least one virtual function), do a dynamic_cast<T*> .

if the result is not NULL then you have an object of type T . But a virtual function would be a better way to go IMO.

Note: RTTI will need to be enabled on your compiler (which it will be in the vast majority of situations)

EDIT: Thanks to @Als and @flipchart for additions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM