【问题标题】:C++ initializing array based on constructor parametersC++根据构造函数参数初始化数组
【发布时间】:2016-07-10 16:37:06
【问题描述】:

您好,我是 C++ 新手,我在根据构造函数参数初始化数组时遇到问题。

我想用 C# 做什么:

class Surface
{
    public int[] pixels;

    public Surface(int w, int h)
    {
        pixels = new int[w * h];
    }
}

我现在在 C++ 中拥有的东西:

class Surface
{
    private:
        GLuint pixels[];
    public:
        Surface(int w, int h) {pixels(w * h) } //Initialize pixels based on width and height
        ~Surface();

};

谢谢

【问题讨论】:

  • 你不是很清楚到底是什么问题。您是在询问编译错误吗?另外,我在这两个版本中看到的一个大问题是您没有保存宽度和高度,只保存了总表面积。
  • pixels = new int[w*h] 这将在堆上初始化数组。
  • @JanVanBergen 编辑您的问题以更清楚地了解您的具体要求是个好主意。

标签: c++ arrays constructor


【解决方案1】:

你应该有一个 pixels 的简单指针定义:

class Surface {
    private:
        GLuint* pixels; // <<<<<<
    public:
        Surface(int w, int h) : pixels(new GLuint[w * h]) {}
        ~Surface();
};

或者更好的是std::vector&lt;GLuint&gt; 成员:

class Surface {
    private:
        std::vector<GLuint> pixels; // <<<<<<
    public:
        Surface(int w, int h) : pixels(w * h,0) {}
        ~Surface();
};

或至少一个std::unique_ptr&lt;GLuint[]&gt;:

class Surface {
    private:
        std::unique_ptr<GLuint[]> pixels; // <<<<<<
    public:
        Surface(int w, int h) : pixels(new GLuint[w * h]) {}
        ~Surface();
};

【讨论】:

  • unique_ptr 版本在调用错误版本的delete 时会调用UB。
  • @juanchopanza 我的编辑会修复它吗?否则我可能应该完全删除那部分。
【解决方案2】:

在 C++ 中,静态数组的大小必须是编译时常量。

解决方案是使用动态数组,因为它的大小不必是编译时常量。

更好的解决方案是对动态数组使用一些抽象,例如std::vector

【讨论】:

    【解决方案3】:

    使用std::vector

    #include  <vector>
    
    class Surface
    {
        private:
            std::vector<GLuint> pixels;
        public:
            Surface(int w, int h) : pixels(w * h) { }
    };
    

    如果您改用new[],则必须手动管理数组的分配、复制和释放:

    class Surface
    {
        private:
            GLuint *pixels;
            int numPixels;
        public:
            Surface(int w, int h) : numPixels(w*h), pixels(new GLuint [numPixels]) { }
            Surface(const Surface &src) : numPixels(src.numPixels), pixels(new GLuint[numPixels]) { std::copy(src.pixels, src.pixels + numPixels, pixels); }
            ~Surface() { delete[] pixels; }
            Surface& operator=(const Surface &lhs) { Surface temp(lhs); std::swap(temp.pixels, pixels); std::swap(temp.numPixels, numPixels); return *this; }
    };
    

    【讨论】:

      【解决方案4】:

      在 C++ 中没有变长数组这样的东西。所有数组都有固定的长度。由于您需要一个可变长度数组,因此您必须改用std::vector

      std::vector<GLuint> pixels;
      

      并且构造可以使用resize() 来调整向量的大小:

      Surface(int w, int h) {
          pixels.resize(w * h);
      }
      

      【讨论】:

      • 向量有一个将计数作为输入的构造函数。因此,您可以在初始化列表中初始化向量,而不是在构造函数主体中使用resize ()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多