【问题标题】:Passing an int to a function, then using that int to create an array将 int 传递给函数,然后使用该 int 创建数组
【发布时间】:2015-08-31 15:00:21
【问题描述】:

我正在尝试为我的 openGL 项目创建一个 textureLoader 类,但我无法在我的类构造函数中初始化一个纹理数组,因为该数组不会接受任何内容,除非它是一个 const int。

给你画一幅简单的图画……

myFunction(NUM)
  {
  GLuint textures[NUM];
  }

我过去的失败

myConstructor(const int& num)
  {
   GLuint textures[num] //error: expression must have a constant value
  }

myConstructor(int num)
{
std::vector <GLuint> textures(num);//works but wait
glGenTextures(num, textures) // <--- doesn't work cause vectors. 
}

myConstructor(int num)
{
const int PLEASE_WORK = num;
GLuint textures[PLEASE_WORK]; // doesn't work. 

【问题讨论】:

  • 您尝试的方法(vector 方法除外)称为可变长度数组,C99 支持,但 C++ IIRC 不支持。
  • 我会查一下,谢谢。我在想至少第三种选择应该有效。
  • 不是因为在编译过程中数组的大小是未知的。

标签: c++ arrays opengl


【解决方案1】:

您的第二个选项很接近,您可以通过调用 .data() 来获取向量的底层数组

myConstructor(int num)
{
    std::vector <GLuint> textures(num);
    glGenTextures(num, textures.data());
}

假设glGenTextures 有一个类似的签名

void glGenTextures(int, GLuint*)

我对这个函数了解不多,但要小心谁拥有该数组。 vector 将在您的构造函数之后超出范围,因此我希望 glGenTextures 将复制它需要的任何内容。否则如果数组需要持久化

myConstructor(int num)
{
    GLuint* textures = new GLuint[num];
    glGenTextures(num, textures);
}

但是我不确定谁应该清理那段内存。

【讨论】:

  • 是的,谢谢,我会记住这些变量的范围。有没有办法使用 const int& 或向量以外的任何东西来做到这一点?或者这是我唯一的选择。
  • 仅供参考:std::vector::data 是 c++11
  • @BryantheLion 请参阅我答案的后半部分(使用new),这是您的选择。
  • @Tas 2015 年已经过半了,我希望人们(至少)使用 C++11 编译器,否则他们应该特别指出他们所针对的编译器。
  • @BryantheLion 当然这是一个有效的选项。将指向该数组的指针保留为成员变量,然后在析构函数中调用 delete[] your_array
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 2021-11-26
  • 1970-01-01
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多