سؤال

I know that has been asked a lot, I googled but couldn't put everything together. Maybe because it is not possible to do, what I want?

I have

struct Universe
{
}

and

struct Atom: Universe
{
}

struct Molecule: Universe
{
}

Universe U;
Atom A;
Molecule M;
_atoms =  vector<Universe*>(3);
_atoms.push_back(&U);
_atoms.push_back(dynamic_cast<Universe*>(&A));
_atoms.push_back(dynamic_cast<Universe*>(&M));

auto THIS_IS_ATOM = _atoms[1];

This code is most likely wrong in many ways. But my idea was to store different derived structs like this, and later access them from array or list, without any dataloss or class truncating. I wanted to get some element from array, like _atoms[1], and be able to know what type this struc is (Universe, or Atom) and e.t.c

How should I do it properly in C++?

هل كانت مفيدة؟

المحلول

Your code has several problems.

  1. Universe needs a virtual destructor.
  2. You must create your instances on the heap.
  3. You are using the wrong std::vector constructor.

Here is a solution that should work:

struct Universe {
    virtual ~Universe() {} // otherwise Atom and Molecule will not be deleted properly
}

struct Atom : Universe {

}

struct Molecule : Universe { 

}

std::vector<Universe*> _atoms; // you don't need to pass anything in the constructor
_atoms.reserve(3); // but if you want to make sure that the vector has exactly a capacity of 3, use this

_atoms.push_back(new Universe());
_atoms.push_back(new Atom());
_atoms.push_back(new Molecule());

auto this_is_atom = _atoms[1]; // will actually be equivalent to
Universe* this_is_atom = _atoms[1];

// finally you must delete all the instances which you created on the heap
while (!_atoms.empty()) delete _atoms.back(), _atoms.pop_back();

Addendum: If you need to treat the objects in the vector non-polymorphically, you can cast them to the appropriate types with a static cast:

Atom* a = static_cast<Atom*>(_atoms[1]);

Edit: Instead of using a vector of raw pointers, it is advisable to use a vector of smart pointers instead, for example std::unique_ptr or std::shared_ptr, depending on the ownership semantics you are trying to model.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top