初学C++:运行时创建对象而不知道要创建多少个对象
假设我有一个定义为“MyClass”的类。我的“main”方法将文件名列表作为参数。每个文件名都是 MyClass 的配置文件,但程序用户可以拥有任意数量的 MyClass 对象。如果他们输入 2 个文件名作为我的 main 方法的参数,我想要 2 个对象。
如果我知道用户仅限于 2 个对象,我可以使用:
MyClass myclass1;
MyClass myclass2;
但是,如果用户输入 3 或 4 个文件名,则这将不起作用。任何人都可以帮助我并建议一种方法,我可以使用该方法根据我的程序给出的参数数量来创建类的多个实例化?
谢谢
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 filenames 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
std::vector
。示例之后,您可以通过
[]
和迭代器等访问元素。网络上有很好的参考资料。Use
std::vector
. ExampleAfter that you can access the elements via
[]
and iterators and much more. There are excellent references on the web.您可以使用
MyClass
实例的std::vector
- 然后您可以根据需要创建任意数量的实例。例如,看看本教程(一个网上有很多),帮助您入门。
You could use a
std::vector
ofMyClass
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.
为此,您应该使用数组或向量:
然后您可以像这样访问它们:
请参阅维基百科以获取更多信息和示例:
http://en.wikipedia.org/wiki/Vector_%28C%2B%2B%29#Usage_example
For this, you should use arrays or vectors:
And then you can access them like:
See wikipedia for more info and examples:
http://en.wikipedia.org/wiki/Vector_%28C%2B%2B%29#Usage_example