无法分配C++数组

Can't assign C++ array

本文关键字:数组 C++ 分配      更新时间:2023-10-16

上下文:需要在 TestTextures3SpriteObj s1 中将 verts 设置为 verts1 数组。给我一个错误"表达式必须是可修改的左值"。复制后,顶点将作为 OpenGL 和 GLUT 的缓冲区数据发送到 GPU。

仅包含相关的代码摘录

#pragma once
class TestTextures3SpriteObj
{
public:
int spriteid;
int vao;
int texid;
float verts[];
};

const float verts1[] = { 0.5 ,0.5, 0.0, 0.9, 0.5, 0.3, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.3, 0.3, 0.9, 1.0, 1.0, 1.0,
-0.5, -0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0,
-0.5, 0.5, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0 };

TestTextures3SpriteObj s1;

s1.verts = verts1;

实际上您没有访问该变量...

如果要访问单个元素,请使用索引

s1.verts1[0]

如果要复制,请使用std::copy

std::copy(verts1, verts1 + 36, s1.verts);
#include <iostream>
using namespace std;
class TestTextures3SpriteObj
{
public:
int spriteid;
int vao;
int texid;
float verts[36]; //assign the size to the array
};

const float verts1[] = { 0.5 ,0.5, 0.0, 0.9, 0.5, 0.3, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.3, 0.3, 0.9, 1.0, 1.0, 1.0,
-0.5, -0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0,
-0.5, 0.5, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
int main()
{
TestTextures3SpriteObj s1;
int len=sizeof(verts1)/sizeof(verts1[0]);
//copies the entire array to the object with member verts
std::copy(verts1, verts1 + 36, s1.verts);
//printing the values in the s1 object
for(int i=0;i<len;i++)
{
cout<<s1.verts[i]<<" ";
}
}

为类中的数组分配一个大小,然后执行 std::copy 以复制 verts 数组中的值。