我有一些这样的代码:
class MyObject {
private:
int x;
public:
MyObject(int x) : x(x) {}
};
我想初始化 5 个 MyObject
实例。我知道我可以使用 g++ 8.3.0 做到这一点。
MyObject obj_array[5]{1, 2, 3, 4, 5};
但是,我无法做到这一点:
const int myInts[5] = {1, 2, 3, 4, 5};
MyObject obj_array[5](myInts);
有什么方法可以使第二种初始化方法(使用 const 整数数组通过初始化列表构造函数初始化对象数组)起作用吗?问题是我们有一个特殊的编译器框架,它不允许动态内存或大多数 STL 数据类型,例如 vector
。
最佳答案
如果我们正在做丑陋的解决方案,这里有一个具有可扩展性的解决方案:
#define LIST { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
const int myInts[] = LIST;
MyObject obj_array[] = LIST;
#undef LIST
关于具有 const 初始值设定项列表的 C++ 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59276075/