Declare and initialize a struct / class array at the same time

1.

I know that in an ad you can initialize an array of structures. For example:

struct BusStruct
{
    string registration_number;
    string route;
};

struct BusStruct BusDepot[] =
{
    { "ED3280",    "70" },
    { "ED3536",    "73" },
    { "FP6583",    "74A" },
};

If the structure is changed into a class, for example:

class BusClass
{
protected:
    string m_registration_number;
    string m_route;
public:
    // maybe some public functions to help initialisation
};

Is it possible to do the same as for the structure (i.e., declare and initialize an array of classes at the same time)?

2. Do I believe that it is impossible to declare and initialize, vector<BusStruct>or vector<BusClass>at the same time?

+3
source share
3 answers

Is it possible to do the same as for the structure (i.e., declare and initialize an array of classes at the same time)?

Not unless you created a suitable constructor:

class BusClass
{
protected:
    string m_registration_number;
    string m_route;
public:
    // maybe some public functions to help initialisation
    // Indeed:
    BusClass(string const& registration_number, 
             string const& route)
    :m_registration_number(registration_number),
     m_route(route) { }
};

, , . , , .

, vector<BusStruct> vector<BusClass> ?

, ++. , . Boost.Assign . , , , . - factory

BusStruct make_bus(string const& registration_number, 
                   string const& route) { ... }

.

+3
  • , , , . .
  • ++ , , .
+1

C ++ natively supports two forms of vector initialization, and not what you are looking for.

1: Each item is the same as in:

vector<int> ints(4,1000); //creates a vector of 4 ints, each value is 1000.

2: Copy from an existing vector, as in:

vector<int> original(3,1000); //original vector has 3 values, all equal 1000.
vector<int> otherVector(original.begin(),original.end()); //otherVector has 3 values, copied from original vector
0
source

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


All Articles