There is an abstract class "Organism". It is inherited by 2 classes: "Animals" and "Plants"
How can you store objects of the classes "Animals" and "Plants" in 1 array \ vector \ something else
There is an abstract class "Organism". It is inherited by 2 classes: "Animals" and "Plants"
How can you store objects of the classes "Animals" and "Plants" in 1 array \ vector \ something else
Since this is most likely a computer game, and the Animals and Plants class will be represented as control objects, it is best to use the pattern factory to create the objects themselves, and store their pointers in std :: list or std :: forward_list, since the speed of insertion and deletion (birth, death) of the element will be constant.
*Animal and *Plant are different types. Do you suggest that *void lead them? It is wildly dangerous, the best in any store. But it still does not solve a bunch of problems. For example, it’s impossible to make a call to l[1].call() , you can only std::any_cast<Animal>(l[1]).call() - Andrio Skur #include <iostream> #include <vector> #include <memory> using namespace std; // Вначале объявим базовый класс class Organism { public: virtual string name() = 0; virtual ~Organism() = default; }; // наследники class Animal : public Organism { public: string name() override { return "Animal"; } }; class Plant: public Organism { public: string name() override { return "Plant"; } }; int main() { // так как на дворе 2018, то пишем на 11 стандарте и используем умные указатели vector<unique_ptr<Organism>> org; // и добавление без new org.push_back(make_unique<Plant>()); org.push_back(make_unique<Animal>()); // а вот здесь объязательно нужно const и &, так как unique_ptr for (const auto& o : org) { // name - виртуальная, поэтому никаких dynamic_cast cout << o->name() << endl; } // и память за нас компилятор освободит. return 0; } Perhaps in the future, you will need to replace the unique_ptr with shared_ptr.
Or is it still a school task and the teacher will compile in turbo c ++ 3?
// Создадим массив и добавим в него одно животное и два растения: std::vector<Organism*> mas; mas.push_back(new Plant); mas.push_back(new Animal); mas.push_back(new Plant); // Узнаем, то, что лежит ли в mas[1] это растение или животное: if (dynamic_cast<Plant*>(mas[1])) { std::cout << "this is Plant" << std::endl; } else if (dynamic_cast<Animal*>(mas[1])) { std::cout << "this is Animal" << std::endl; } else { std::cout << "this is unknown Organism" << std::endl; } // Удаление: for (int i = 0; i < mas.size(); ++i) { delete mas[i]; } mas.clear(); // Если всё было сделано верно, и деструктор класса Organism был объявлен как виртуальный, то delete вызовет правильный деструктор и утечки памяти не будет Source: https://ru.stackoverflow.com/questions/812343/
All Articles