【问题标题】:Initialize pointer to array初始化指向数组的指针
【发布时间】:2013-03-21 16:41:28
【问题描述】:

我正在尝试在我的类构造函数中初始化指向结构数组的指针,但它根本不起作用...

class Particles {

private:

    struct Particle {
        double x, y, z, vx, vy, vz;
    };

    Particle * parts[];

public:

    Particles (int count)
    {
        parts = new Particle [count]; // < here is problem
    }

};

【问题讨论】:

  • 你有什么问题?
  • 这不是指向数组的指针,而是指向Particle 的指针数组。见this
  • 使用std::vector&lt;Particle&gt; 代替动态分配的数组可以省去很多麻烦。

标签: c++


【解决方案1】:

从声明中删除那些[]。应该是

Particle *parts;

使用C++,可以使用std::vector的好处:

class Particles {
  // ...

 std::vector<Particle> parts;

 public:

    Particles (int count) : parts(count)
    {

    }
};

【讨论】:

  • @balki 否,因为count 不是编译时间常数。但是std::vector&lt;Particle&gt; 会很好。
【解决方案2】:
Particle * parts[];

这是一个指针数组。要初始化它,您需要遍历数组,初始化每个指针以指向动态分配的 Particle 对象。

您可能只想将parts 设为指针:

Particle* parts;

new[] 表达式返回一个指向数组第一个元素的指针 - 一个 Particle* - 所以初始化工作正常。

【讨论】:

    【解决方案3】:

    试试这个:

    类粒子{

    私人:

    struct Particle {
        double x, y, z, vx, vy, vz;
    };
    
    Particle * parts;
    

    公开:

    Particles (int count)
    {
        parts = new Particle [count]; // < here is problem
    }
    

    };

    【讨论】:

      猜你喜欢
      • 2010-10-11
      • 2015-04-28
      • 2012-12-19
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      相关资源
      最近更新 更多