简体   繁体   中英

How to create an array of objects with parameterized constructor

I need to create an array of objects with non default constructor. What language feature should be applied to achieve this?

This line of code doesn't let me do that.

Object objects[10]{("foo", "bar")};

Unless you want to specify all individual objects in the initializer list, it's not really possible with plain simple arrays.

However with a std::vector it is dead simple, because there is a constructor overload that takes the size of the vector and the object to initialize all elements to. So you can do something like

std::vector<Object> objects(10, Object("foo", "bar"));

The above will create a vector with ten elements, all elements initialized to copies of Object("foo", "bar") .

You can use vector or array of pointers on your object.

Object* arr[6];
for (int i = 0; i < 6; i++)
{
     arr[i] = new Object("angry dog", 6);
}

Use = and pass your values for non-default ctor in initializer list. This way you should define every value in the array, though.

Example

int main()
{
    struct A {
        int _v;

        A(int v) : _v(v) {}
    };

    A my_a[3] = {0, 1, 2};

    for (auto i : my_a)
      std::cout << i._v << ", ";
    std::cout << "\n";

}

Short answer is there is no way to do that with raw array. An alternative way would be to use std::vector which offers that possibility.

Something like this?

#include <array>
#include <iostream>

struct foo {
    int a, b;
};

int main()
{
  std::array<foo, 4>  v= {{ {1, 2}, {2, 3}, {3, 4}, {4, 5} }};
  for (auto f : v) {
      std::cout << f.a << ' ' << f.b << std::endl;
  }
}

Using Double pointer (pointer to pointer concept): A pointer to a pointer is a form of multiple indirections, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. Here we can assign a number of blocks to be allocated and thus for every index we have to call parameterised constructor using the new keyword to initialise

#include <iostream> 
#include <string>
#define N 5 
  
using namespace std; 
  
class Test { 
    // private variables 
    string x, y; 
  
public: 
    // parameterised constructor 
    Test(string x, string y) 
    { 
        this->x = x; 
        this->y = y; 
    } 
  
    // function to print 
    void print() 
    { 
        cout << x << " " << y << endl; 
    } 
}; 
  
int main() 
{ 
    // allocating array using 
    // pointer to pointer concept 
    Test** arr = new Test*[N]; 
  
    // calling constructor for each index 
    // of array using new keyword 
    for (int i = 0; i < N; i++) { 
        arr[i] = new Test(to_string(i), to_string(i + 1)); 
    } 
  
    // printing contents of array 
    for (int i = 0; i < N; i++) { 
        arr[i]->print(); 
    } 
  
    return 0; 
} 

ARRAY in C++ can means different things. array<T, int> for fixed sized array added in C++11, raw array of objects T[] (same as T*), or vector.

  1. array<T, 3> = { } you can explicitly initialize each object, such as string("ad") inside the curly bracket.
  2. T* or T[] this you cannot do, only way is to initialize with default constructor.
  3. T** or T*[], you can initialize wit any parameterized constructor of T
  4. vector You can use emplace(v.end(), args...) [optionally in a loop] to initialize to the same or variable parameters. This may be more efficient than 3 because in 3 objects may be dispersed in different memory locations.

The above list may not be complete, and there might be mistakes. The intention is to start this thread of thinking and welcome others to correct and improve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM