Beginner C++: object creation at runtime without knowing how many objects to create
Say I have a class I defined called 'MyClass'. My 'main' method takes as arguments a list of filenames. Each filename is a config file for MyClass, but the program user can have as many objects of MyClass as they want. If they type in, say, 2 filen开发者_如何学Pythonames as arguments to my main method, I would like to have 2 objects.
If I knew the user was limited to 2 objects, I could just use:
MyClass myclass1;
MyClass myclass2;
However this wouldn't work if the user had say inputted 3 or 4 filenames instead. Can anyone help me and suggest a method I could use to create a number of insantiations of a class depending on the number of arguments my program is given?
Thanks
Use std::vector
. Example
#include <vector>
std::vector<MyClass> vec;
vec.push_back(MyClass());
vec.push_back(MyClass());
vec.push_back(MyClass());
After that you can access the elements via []
and iterators and much more. There are excellent references on the web.
You could use a std::vector
of MyClass
instances - then you could make as many or as few as you wanted.
Take a look at this tutorial, for example (one of many out there on the web), to get you started.
For this, you should use arrays or vectors:
vector<MyClass> myclass;
myclass.push_back( ... ); // Make your objects, push them into the vector.
myclass.push_back( ... );
myclass.push_back( ... );
And then you can access them like:
myclass[0];
myclass[1];
...
See wikipedia for more info and examples:
http://en.wikipedia.org/wiki/Vector_%28C%2B%2B%29#Usage_example
精彩评论