简体   繁体   中英

Creating multiple objects and passing parameters through constructor

I am trying to understand how to create multiple objects(20 in the current case) and pass parameter to the constructor as shown in the comments of the code. Unfortunately, I cannot pass parameters as well as have an array of objects at the same time.

I tried this as well to create the object convector con(100,200, construct(20)); but it didn't seem to give the desired result

#include <iostream>

class construct { 
public: 
    int a, b; 

    // Default Constructor 
    construct(int x1,int x2) 
    { 
         a = x1; 
         b = x2; 
    } 
    int getX1(){
        return a;
    }
    int getX2(){
        return b;
    }
};  
int main(){
    int p,q;
    construct* con = new construct[20](100,200);

for (unsigned int i = 0; i < 20; i++) {
    p=con[i]->getX1();
        q=con[i]->getX2();
        printf("%d %d \n",p,q);
    }
    delete con;
    return 1;
}

Expected result would be 20 objects created.

Just use std::vector . Seriously, there's no reason not to.

std::vector<construct> con(20, {100, 200});

Yeah, for this you are likely to need placement new sadly (or use std::vector, and pass a newly constructed object as the second argument).

// call global new (effectively malloc, and will leave objects uninitialised)
construct* con = (construct*)::operator new (sizeof(construct) * 20);

// now call the ctor on each element using placement new
for(int i = 0; i < 20; ++i)
  new (con + i) construct(100, 200);

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