Storing a list of arbitrary objects in C++

前端 未结 13 2038
野趣味
野趣味 2021-02-06 08:29

In Java, you can have a List of Objects. You can add objects of multiple types, then retrieve them, check their type, and perform the appropriate action for that type.
For e

13条回答
  •  悲哀的现实
    2021-02-06 08:55

    RTTI (Run time type info) in C++ has always been tough, especially cross-compiler.

    You're best option is to use STL and define an interface in order to determine the object type:

    public class IThing
    {
       virtual bool isA(const char* typeName);
    }
    
    void myFunc()
    {
       std::vector things;
    
       // ...
    
       things.add(new FrogThing());
       things.add(new LizardThing());
    
       // ...
    
       for (int i = 0; i < things.length(); i++)
       {
           IThing* pThing = things[i];
    
           if (pThing->isA("lizard"))
           {
             // do this
           }
           // etc
       }
    }
    

    Mike

提交回复
热议问题