构造数组

Constructing array

本文关键字:数组      更新时间:2023-10-16

如何在运算符new[]中调用特定的类构造函数?

#include <iostream>
class foo
{
public:
foo(){std::cout << "nfoo::foo()n";}
foo(int param){std::cout << "nfoo::foo(int)n";}
};
int main()
{
foo* my_array = new foo[45];
return 0;
}

foo* my_array = new foo[45];会调用foo()构造函数。如何调用foo(int)构造函数?

对于原始数组,没有办法做到这一点。你可以用std::vectors'获得类似的结果。explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type());

std::vector<foo> my_vector(45, 10);

将创建包含 45 个foo对象的 Vector,每个对象都通过构造函数调用创建foo(10)