c++ - Instance object with a array -
i'm working in c++ class :
class foo { int ; foo (){ = rand(); } foo(int b){ a=b } }; int main(){ foo * array = new foo[10]; //i want call constructor foo(int b) // foo * array = new foo(4)[10]; ???? }
please , :d
you should first correct syntax (put ;
, make constructors public
etc). then, can use uniform initialization in c++11, like
#include <iostream> class foo { public: int a; foo () { } foo(int b) { = b; } }; int main() { foo * array = new foo[10] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::cout << array[2].a << std::endl; // ok, displays 2 delete[] array; }
you should try avoiding altogether raw arrays, use std::vector
(or std::array
), or other standard container instead. example:
std::vector<foo> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
or
std::vector v(10, 4); // 10 elements, initialized 4
no need remember delete memory etc.
Comments
Post a Comment