Array of pointers

How can I get an array of pointers pointing to objects (classes)?

I need to dynamically allocate space for them, and the length of the array is not determined until runtime. Can someone explain and tell me how to define it? and perhaps explaining to them how it works would be very nice :)

+3
source share
4 answers

You can do this with a pointer to a pointer to your class.

MyClass ** arrayOfMyClass = new MyClass*[arrayLengthAtRuntime];
for (int i=0;i<arrayLengthAtRuntime;++i)
    arrayOfMyClass[i] = new MyClass(); // Create the MyClass here.

// ...
arrayOfMyClass[5]->DoSomething(); // Call a method on your 6th element

Basically, you are creating a pointer to an array of links in memory. The first new one allocates this array. The loop allocates each instance of MyClass to this array.

, std::vector , , , .

+10

std::vector . .

#include <vector>
// ...
std::vector<Class*> vec;
vec.push_back(my_class_ptr);
Class* ptr = vec[0];
+15

boost:: ptr_vector , :

boost::ptr_vector<animal> vec;
vec.push_back( new animal );
vec[0].eat();

, .

+4

, : , . , :

MyClass ** arrayOfMyClass = new MyClass*[arrayLengthAtRuntime];
for (int i=0;i<arrayLengthAtRuntime;++i)
    arrayOfMyClass[i] = new MyClass(); // Create the MyClass here.

// ...
arrayOfMyClass[5]->DoSomething(); // Call a method on your 6th element

I use this method to implement my own dynamic-size arrays (what std :: vector is), mainly because I did not invent the syndrome here, but also because I like to configure them for my specific use.

+3
source

Source: https://habr.com/ru/post/1715459/


All Articles