C++ 如何使用nullptr初始化同一类对象的静态指针数组?
我试图初始化同一类对象的指针数组。下面是课程: 我试过了。但它每次都被初始化C++ 如何使用nullptr初始化同一类对象的静态指针数组?,c++,arrays,class,pointers,C++,Arrays,Class,Pointers,我试图初始化同一类对象的指针数组。下面是课程: 我试过了。但它每次都被初始化 Correspondent::Correspondent(string n,string c) { name = n; country = c; for(int i=0;i<=maxCorrespondents;i++){ correspondent[i] = NULL; } } contractor::contractor(字符串n,字符串c){ name=
Correspondent::Correspondent(string n,string c) {
name = n;
country = c;
for(int i=0;i<=maxCorrespondents;i++){
correspondent[i] = NULL;
}
}
contractor::contractor(字符串n,字符串c){
name=n;
国家=c;
对于(int i=0;i,在定义此变量的一个转换单位中:
Correspondent* Correspondent::correspondent[maxCorrespondents]{};
就是这样。这个聚合初始化数组,数组默认初始化每个指针。由于指针是基本类型,将执行零初始化,将它们全部设置为nullptr
具有静态存储持续时间的对象始终为零初始化。因此对应的数组将填充zer操作系统,无需编写任何附加代码。来自[dcl.init].10
在任何其他初始化发生之前,静态存储持续时间的每个对象在程序启动时初始化为零
另外,最好使用::std::array
包装器,并引入类型别名以避免数组声明和定义中的重复:
class Correspondent
{
private: using Correspondents = ::std::array<Correspondent *, maxCorrespondents>;
private: static Correspondents correspondents;
};
Correspondent::Correspondents Correspondent::correspondents;
类通信
{
私有:使用通讯器=::std::数组;
私人:静态通讯员;
};
通讯员通讯员通讯员通讯员;
class Correspondent
{
private: using Correspondents = ::std::array<Correspondent *, maxCorrespondents>;
private: static Correspondents correspondents;
};
Correspondent::Correspondents Correspondent::correspondents;