【问题标题】:How to initialize static pointer array of objects of same class with nullptr?如何用nullptr初始化同一类对象的静态指针数组?
【发布时间】:2017-12-11 10:07:14
【问题描述】:

我正在尝试初始化相同类对象的指针数组。这是课程:

class Correspondent{
    private:
        static Correspondent *correspondent[maxCorrespondents];
}

我试过在constructor。但它每次都会被初始化。

Correspondent::Correspondent(string n,string c) {
    name = n;
    country = c;
    for(int i=0;i<=maxCorrespondents;i++){
        correspondent[i] = NULL;
    }
}

【问题讨论】:

    标签: c++ arrays class pointers


    【解决方案1】:

    在定义此变量的一个翻译单元中:

    Correspondent* Correspondent::correspondent[maxCorrespondents]{};
    

    就是这样。此聚合初始化数组,而数组又默认初始化每个指针。并且由于指针是基本类型,它将进行零初始化,将它们全部设置为nullptr

    【讨论】:

      【解决方案2】:

      具有静态存储持续时间的对象始终初始化为零。所以correspondent 数组将用零填充,而无需编写任何额外的代码。来自 [dcl.init].10

      在任何其他初始化发生之前,每个静态存储持续时间的对象都会在程序启动时进行零初始化。

      使用::std::array 包装器并引入类型别名以避免数组声明和定义中的重复可能是一个好主意:

      class Correspondent
      {
          private: using Correspondents = ::std::array<Correspondent *, maxCorrespondents>;
          private: static Correspondents correspondents;
      };
      
      Correspondent::Correspondents Correspondent::correspondents;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-31
        • 2019-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多