c++ - 将一个 int 传递给一个函数,然后使用该 int 创建一个数组

标签 c++ arrays opengl

我正在尝试为我的 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. 

最佳答案

您的第二个选项很接近,您可以通过调用 .data()

获取 vector 的底层数组
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);
}

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

关于c++ - 将一个 int 传递给一个函数,然后使用该 int 创建一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856630/

相关文章:

c++ - ifstream::read 不追加 '\0'

c++ - 无法从 switch case 语句传递构造函数的参数

c++ - C++标准在哪里说的,C说的是同一个: variables in a compilation unit (. cpp文件)按声明顺序初始化

c - 如何在不同的 if 语句中访问我的结构的元素?

c++ - 将阴影添加到视差遮挡贴图

c++ - C++中的结构和类有什么区别?

android - 从资源中创建数组

python 循环比 numpy 数组操作更快

c++ - 使用 SDL_ttf 和 OpenGL,TTF_RenderUTF8_Blended 打印红色矩形

wpf - 如何在 WPF 中创建偏离中心的 PerspectiveCamera?