将 int 传递给函数,然后使用该 int 创建数组
Passing an int to a function, then using that int to create an array
>我正在尝试为我的 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()
来获取向量的底层数组
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);
}
但是我不确定谁应该清理这段记忆。
相关文章:
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 如何创建一个类,以便向量工作 std::vector<MyClass<int>> v{ 1,2,3 };
- 为什么在创建矩阵时使用" ** int A"而不是" int A" (c++)
- 创建<int>对整数数组指针的矢量引用 (C++)
- 这是在传递 int num 时创建搜索函数的正确方法吗?使用链表库
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 从数组创建 Mat 时,'cv::Mat' 和 'int' 类型不兼容
- 参数包推导不一致 int 和 int& 在可变参数模板化成员函数中创建运行成员函数的线程
- std::map<int, A> 运算符 [] 需要使用空构造函数创建 A
- 为什么我不能使用与"常量字符*"相同的"const int*"创建一个 int 数组?
- QT - 如何创建具有长 int(而不是 int)步长的滚动条?
- 如何正确分配动态创建int并将其分配给具有值的动态数组数组
- 创建具有未定义溢出的无符号 int
- 声明数组时出现 SIGSEGV 错误,而不创建新的 int[size]
- 创建一个包含对 <int、自定义类的最小堆>
- 是否可以使用C 函数中的const int参数创建数组
- 为 map<int、pair<int、int 创建比较器>>
- 为什么'std::vector<int> b{2};'创建 1 元素向量,而不是 2 元素向量?
- 将 int 传递给函数,然后使用该 int 创建数组