Storing a list of arbitrary objects in C++

前端 未结 13 2371
野趣味
野趣味 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:12

    Just for completeness of this topic I want to mention that you can actually do this with pure C by using void* and then casting it into whatever it has to be (ok, my example isn't pure C since it uses vectors but that saves me some code). This will work if you know what type your objects are, or if you store a field somewhere which remembers that. You most certainly DON'T want to do this but here is an example to show that it's possible:

    #include 
    #include 
    
    using namespace std;
    
    int main() {
    
      int a = 4;
      string str = "hello";
    
      vector list;
      list.push_back( (void*) &a );
      list.push_back( (void*) &str );
    
      cout <<  * (int*) list[0] << "\t" << * (string*) list[1] << endl;
    
      return 0;
    }
    

提交回复
热议问题