本文介绍了声明使用for循环C对象的数组++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧。因此,我已宣布对象的数组,并使用该code我已经手动定义它们:
Okay. So I have declared an array of objects, and I have manually defined them using this code:
Object* objects[] =
{
new Object(/*constructor parameters*/),
new Object(/*constructor parameters*/)
};
反正是有(pferably一个$ P $循环)使用某种循环的声明这些?是这样的:
Is there anyway to use some kind of a loop (preferably a for loop) to declare these? Something like:
Object* objects[] =
{
for(int i=0; i<20; /*number of objects*/ i++)
{
new Object(/*constructor parameters*/);
}
};
但随着正确的语法?
But with proper syntax?
推荐答案
我强烈建议使用标准库容器,而不是数组和指针:
I strongly suggest using a standard library container instead of arrays and pointers:
#include <vector>
std::vector<Object> objects;
// ...
void inside_some_function()
{
objects.reserve(20);
for (int i = 0; i < 20; ++i)
{
objects.push_back(Object( /* constructor parameters */ ));
}
}
这提供了在堆上异常的安全性和更小的压力。
This provides exception-safety and less stress on the heap.
这篇关于声明使用for循环C对象的数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!