结构C++ 、动态名称构造
我在 C++ 类中构造了一个结构, 让我们坐在它称为任务
我想启动一个基于索引的新构造,每次运行程序时该索引可能会改变,例如
for ( i=1; i<=index,++i){
Task ai;
}
在循环之后我希望有名为a1,a2,a3,a4的结构, ...an
如何将数字 i 添加到名称末尾作为名称的一部分。
I have constructed a struct in a C++ class,
Lets sat it is called Task
I would like to initiate a new constructed based on an index that might change every time I run the program, for example
for ( i=1; i<=index,++i){
Task ai;
}
this way after the loop I would like to have structures named a1, a2, a3 ,a4,...an
How can I add the number i to the end of the name as a part of it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C++没有反射,所以不能像这样动态创建变量名。然而,数组/向量在这里很有用:
C++ does not have reflection, so you can't dynamically create variable names like this. However, arrays/vectors are useful here:
如前所述,您可以使用
std::vector
,尽管我可能只使用动态分配的数组:As mentioned you could use an
std::vector<Task>
, although I would probably just use a dynamically allocated array:使用 std::vector <任务> ai 并将其添加到向量中。这也可以解决索引变化的问题。
Use a std::vector < Task > ai and add it to the vector. This would solve the problem of varying index too.