在C++中将指针数组的所有元素设置为 nullptr

Setting all elements of an array of pointers to nullptr in C++

本文关键字:元素 设置 nullptr C++ 指针 数组      更新时间:2023-10-16

我只是想知道是否有一种方法可以在不使用循环的情况下设置指向所有空值的初始化指针数组?

class Abc{
//An array of 2000 Product pointers
Product* product_[2000];
public:
Abc();
}

我想在调用构造函数时将所有指针设置为 null:

Abc::Abc(){
product_ = {};
}

这不起作用,product_必须是可修改的值。 有没有比循环 2000 个元素更简单的方法?

谢谢。

您可以使用:

class Abc{
//An array of 2000 Product pointers
Product* product_[2000];
public:
Abc() : product_{} {}
};

如果你使用 std::array,它们将默认初始化为 nullptr。

std::array<Product *, 2000> product;

使用Visual Studio编译器,您可以在初始值设定项列表中初始化指向NULL的指针,如下所示-

class Abc{
//An array of 2000 Product pointers
Product* product_[2000];
public:
Abc():product_(){};
}