如何在数组中使用类私有变量

时间:2019-11-25 09:06:16

标签: c++ c++11

我希望我的数组具有类成员作为输入数据,并在类函数中使用它。

GLfloat verticesRect[] = {
    // Positions             // Normal Coords     // Texture Coords
    width,  height, 0.0f,    0.0 , 0.0, 1.0 ,     1.0f, 0.0f,   // Top Right
    width, -height, 0.0f,    0.0 , 0.0, 1.0 ,     1.0f, 1.0f,   // Bottom Right
   -width, -height, 0.0f,    0.0 , 0.0, 1.0 ,     0.0f, 1.0f,   // Bottom Left
   -width,  height, 0.0f,    0.0 , 0.0, 1.0 ,     0.0f, 0.0f    // Top Left 
};

目前,我在所有函数中都将数组声明为局部变量,我可以只声明一次然后使用它。

class test
{
  private:
    width;
    height;

public:
   init();  // this function will use the vertices
   getMesh() // this function will use the vertices

};

1 个答案:

答案 0 :(得分:0)

假设可以将成员变量“通过引用”放入数组中,从而使数组中的值根据成员变量而变化为假。您需要手动执行此操作。

您可以将数组存储为类成员,并为widthheight使用setter来相应地更新值。

class test
{
  private:
    GLfloat width;
    GLfloat height;
    std::array<GLfloat, 4 * (3 + 3 +2)> verticesRect; // Array for 4 vertices, with 8 values each

  public:
    init() {
        // this function will use the vertices
        doStuff(this->verticesRect.data()); // In case you need a GLfloat* use data()
    }
    getMesh(); // this function will use the vertices

    void setWidth(GLfloat value) {
        //Update local variable
        this->width = value;
        //update data of the array
        this->verticesRect[0] = value;
        this->verticesRect[8] = value;
        this->verticesRect[16] = value;
        this->verticesRect[24] = value;
    }

    void setHeight(GLfloat value) {
        //analogus to setWidth()
        //...
    }
};
相关问题