我正在尝试初始化相同类对象的指针数组。这是类:
class Correspondent{
private:
static Correspondent *correspondent[maxCorrespondents];
}
我尝试了控制。 但它每次都被初始化。
Correspondent::Correspondent(string n,string c) {
name = n;
country = c;
for(int i=0;i<=maxCorrespondents;i++){
correspondent[i] = NULL;
}
}
在定义此变量的一个翻译单元中:
Correspondent* Correspondent::correspondent[maxCorrespondents]{};
就是这样。此聚合初始化数组,而数组又默认初始化每个指针。而且由于指针是基本类型,这将执行零初始化,将它们全部设置为nullptr
.
具有静态存储持续时间的对象始终为零初始化。因此correspondent
数组将填充零,而无需编写任何其他代码。来自[dcl.init].10
进行任何其他初始化之前,每个静态存储持续时间的对象在程序启动时都初始化为零。
此外,使用::std::array
包装器并引入类型别名以避免数组声明和定义中的重复也可能是一个好主意:
class Correspondent
{
private: using Correspondents = ::std::array<Correspondent *, maxCorrespondents>;
private: static Correspondents correspondents;
};
Correspondent::Correspondents Correspondent::correspondents;