Can you create objects using variables in C ++

I want to create several class objects, but this number will not be known until execution. Intuition tells me that I should use the following loop to create my objects:

for (int count = 0;  count < no_of_objects; count ++)
{
    ClassName object_name[count]
}

This, however, does not work, as the compiler does not seem to like using variables as object names. Is there a way to create these objects using a loop, or do I need to use some other method.

Please keep in mind that I have not used C ++ for a long time and was recently introduced to programming, so my knowledge of the language is somewhat limited - until now, the array was the only data structure that I taught - there are no vectors, etc.

+3
source share
4

:

std::vector<ClassName> objects (no_of_objects);

[0] [no_of_objects - 1]; , objects.size() no_of_objects. , .., (< vector) , .

+6

++ , . , :

ClassName* pmyClasses = new ClassName[no_of_objects];

, .

for (int i=0; i < no_of_objects; i++)
{
    pmyClasses[i] = new ClassName();
}

:

for (int i=0; i < no_of_objects; i++)
{
     pmyClasses[i].SomeFunction();
}

, new , delete . , delete [].

for (int i=0; i < no_of_objects; i++)
{
    delete pmyClasses[i];
}
delete [] pmyClasses;

, :

class UsingMyClass
{
    private:
        ClassName* pmyClasses;

    public:
        UsingMyClass(int no_of_objects)
        {
            pmyClasses = new ClassName[no_of_objects];
            for (int i=0; i < no_of_objects; i++)
            {
                 pmyClasses[i] = new ClassName();
            }
        }

        ~UsingMyClass()
        {
            for (int i=0; i < no_of_objects; i++)
            {
                 delete pmyClasses[i];
            }

            delete [] pmyClasses;
        }
 }

, UseMyClass (, new malloc), ClassName .

+2

( ), new i.e. new ClassName[some_number] - ClassName*).

, new new .

0
source

To dynamically allocate memory, you need to use the keyword new

ClassName = new object_name[count];

and be sure to undo the memory after using the deletekeyword

0
source

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


All Articles