Friday, 15 June 2012

c++ - Object array initialization without default constructor -



c++ - Object array initialization without default constructor -

#include <iostream> class auto { private: car(){}; int _no; public: car(int no) { _no=no; } void printno() { std::cout<<_no<<std::endl; } }; void printcarnumbers(car *cars, int length) { for(int = 0; i<length;i++) std::cout<<cars[i].printno(); } int main() { int userinput = 10; auto *mycars = new car[userinput]; for(int =0;i < userinput;i++) mycars[i]=new car[i+1]; printcarnumbers(mycars,userinput); homecoming 0; }

i want create auto array next error:

cartest.cpp: in function ‘int main()’: cartest.cpp:5: error: ‘car::car()’ private cartest.cpp:21: error: within context

is there way create initialization without making car() constructor public?

nope.

but lo! if utilize std::vector<car>, should (never ever utilize new[]), can specify how elements should constructed*.

*well sort of. can specify value of create copies of.

like this:

#include <iostream> #include <vector> class auto { private: car(); // if don't utilize it, can declare create private int _no; public: car(int no) : _no(no) { // utilize initialization list initialize members, // not constructor body assign them } void printno() { // utilize whitespace, itmakesthingseasiertoread std::cout << _no << std::endl; } }; int main() { int userinput = 10; // first method: userinput copies of car(5) std::vector<car> mycars(userinput, car(5)); // sec method: std::vector<car> mycars; // empty mycars.reserve(userinput); // optional: reserve memory upfront (int = 0; < userinput; ++i) mycars.push_back(car(i)); // ith element re-create of // homecoming 0 implicit on main's no homecoming statement, // useful snippets , short code samples }

with additional function:

void printcarnumbers(car *cars, int length) { for(int = 0; < length; i++) // whitespace! :) std::cout << cars[i].printno(); } int main() { // ... printcarnumbers(&mycars[0], mycars.size()); }

note printcarnumbers should designed differently, take 2 iterators denoting range.

c++ arrays constructor

No comments:

Post a Comment