初学C++:运行时创建对象而不知道要创建多少个对象

发布于 2024-12-10 06:27:22 字数 328 浏览 0 评论 0原文

假设我有一个定义为“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南城旧梦 2024-12-17 06:27:22

使用std::vector。示例

#include <vector>

std::vector<MyClass> vec;
vec.push_back(MyClass());
vec.push_back(MyClass());
vec.push_back(MyClass());

之后,您可以通过 [] 和迭代器等访问元素。网络上有很好的参考资料。

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.

人│生佛魔见 2024-12-17 06:27:22

您可以使用 MyClass 实例的 std::vector - 然后您可以根据需要创建任意数量的实例。

例如,看看本教程(一个网上有很多),帮助您入门。

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.

清晨说晚安 2024-12-17 06:27:22

为此,您应该使用数组或向量:

vector<MyClass> myclass;

myclass.push_back( ... );  // Make your objects, push them into the vector.
myclass.push_back( ... );
myclass.push_back( ... );

然后您可以像这样访问它们:

myclass[0];
myclass[1];

...

请参阅维基百科以获取更多信息和示例:

http://en.wikipedia.org/wiki/Vector_%28C%2B%2B%29#Usage_example

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文