在 C++ 中,堆栈上不可能有一个大小在运行时确定的数组。在这里,您使用 std::vector 来做到这一点:
int N = 10;
std::vector<Object> obj(N);
// non-default ctor: std::vector<Object> obj(N, Object(a1, a2));
// now they are all initialized and ready to be used
如果在编译时知道大小,则可以继续使用普通数组:
int const N = 10;
Object obj[N];
// non-default ctor: Object obj[N] =
// { Object(a1, a2), Object(a2, a3), ... (up to N times) };
// now they are all initialized and ready to be used
如果你被允许使用 boost,最好使用 boost::array ,因为它提供了像容器一样的迭代器,你可以使用 .size() 来获取它的大小:
int const N = 10;
boost::array<Object, N> obj;
// non-default ctor: boost::array<Object, N> obj =
// { { Object(a1, a2), Object(a2, a3), ... (up to N times) } };
// now they are all initialized and ready to be used