问题
I have class named Novel. I can declare array of objects as mentioned below:
Novel obj;
but problem is Novel has constructor which I want to be called for all indexes of array how can I do that. I tried following but it does not work.
Novel obj(i,n)[2];
回答1:
You need to use a proper container that uses dynamic allocation to defer construction of individual elements.
std::vector<Novel> objs(2, Novel(i,n));
- http://en.cppreference.com/w/cpp/container/vector/vector
回答2:
Unfortunately the C++ language does not provide that capability. Arrays are allocated, but by default they are not initialised at all. If they are allocated in static storage they get filled with zeros; you can give a brace-initialiser; and you can provide a default constructor to initialise each value. What you cannot do is initialise an array with any other constructor.
To achieve a similar effect you have to approach the problem from a different angle. Basically, you can: - write a macro or template that both allocates an array and calls a constructor on each element under the covers, or - create an object with array semantics, which can initialise itself any way you like.
The built in collection classes are usually the best solution. For example, std::vector provides fill, range and copy constructors as well as array semantics. One of the other answers provides an example, but there are several ways to do it.
std::vector<Novel> objs(2, Novel(i,n));
It's not an array, but it should do what you need.
来源:https://stackoverflow.com/questions/23290873/array-of-objects-with-constructor