Storing a list of arbitrary objects in C++

前端 未结 13 2025
野趣味
野趣味 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 09:07

    I'd just like to point out that using dynamic type casting in order to branch based on type often hints at flaws in the architecture. Most times you can achieve the same effect using virtual functions:

    class MyData
    {
    public:
      // base classes of polymorphic types should have a virtual destructor
      virtual ~MyData() {} 
    
      // hand off to protected implementation in derived classes
      void DoSomething() { this->OnDoSomething(); } 
    
    protected:
      // abstract, force implementation in derived classes
      virtual void OnDoSomething() = 0;
    };
    
    class MyIntData : public MyData
    {
    protected:
      // do something to int data
      virtual void OnDoSomething() { ... } 
    private:
      int data;
    };
    
    class MyComplexData : public MyData
    {
    protected:
      // do something to Complex data
      virtual void OnDoSomething() { ... }
    private:
      Complex data;
    };
    
    void main()
    {
      // alloc data objects
      MyData* myData[ 2 ] =
      {
        new MyIntData()
      , new MyComplexData()
      };
    
      // process data objects
      for ( int i = 0; i < 2; ++i ) // for each data object
      {
         myData[ i ]->DoSomething(); // no type cast needed
      }
    
      // delete data objects
      delete myData[0];
      delete myData[1];
    };
    

提交回复
热议问题