different types of objects in the same vector array?

后端 未结 4 1132
星月不相逢
星月不相逢 2020-12-19 19:46

I am using an array in a simple logic simulator program and I want to switch to using a vector to learn it but the reference I am using \"OOP in C++ by Lafore\" doesn\'t hav

相关标签:
4条回答
  • 2020-12-19 20:15

    Also, the base class "Gate" should have a virtual destructor else there would be issues while cleaning up the vector and it's contents.

    0 讨论(0)
  • 2020-12-19 20:26

    Yes, that will work - as long as you make run() a virtual function in gate and use the address of operator(&) on a and o as you put them in the vector.

    Be careful about object lifetime issues though. If a and/or o go out of scope then your vector will contain pointers to invalid objects.

    0 讨论(0)
  • 2020-12-19 20:29

    You're half-way there:

    std::vector<gate*> G;
    G.push_back(new ANDgate);
    G.push_back(new ORgate);
    for(unsigned i=0;i<G.size();++i)
    {
        G[i]->Run();
    }
    

    Of course, this way you need to take care to ensure that your objects are deleted. I'd use a vector of a smart pointer type such as boost::shared_ptr to manage that for you. You could just store the address of local objects (e.g. G.push_back(&a)), but then you need to ensure that the pointers are not referenced after the local objects have been destroyed.

    0 讨论(0)
  • 2020-12-19 20:30

    You are using

    vector(gate*) G;
    

    change to

    vector<gate*> G;
    

    and you should do this

    G.push_back(new ANDgate());
    

    or if you use boost use shared_ptrs as vector does quite a lot of copying and naked pointers in a vector can be fatal.

    0 讨论(0)
提交回复
热议问题