如何使用新的[]-操作符调用类的默认构造函数之外的其他东西



如何使用新的[]-操作符来初始化class类型的数组呢?

class Class{
...
}
//this only calls the default Constructor of the class
//but I want to initialize the class with my own defined
//constructor passing various arguments to the constructor 
Class* pClass = new Class[100];

谢谢,欢呼声

塞巴斯蒂安

与其使用new,我建议使用std::vector,然后您可以使用任何您喜欢的构造函数。

例如,如果你有两个版本的构造函数

Class();           // default
Class(int, bool);  // some other

然后你可以说

std::vector<Class> classes{100, Class{5, true}};

这将创建一个包含100个元素的vector,每个元素使用您想要的任何参数调用参数化构造函数。

最新更新