不知道如何访问这些元素
cant figure out how to acces these elements
这是我的标题
#include <SDL.h>
class Grid
{
public:
int** Cells;
int x;
int y;
SDL_Color* palette[255];
Grid(int,int,int);
~Grid();
void DrawGrid(SDL_Renderer*);
void SetPalette(int c, int r, int g, int b, int a);
};
这是我的来源:
Grid::Grid(int a,int b,int s)
{
std::cout << "grid constructed";
x = a;
y = b;
Grid::Cells = (int**) malloc(x*s);
for (int i = 0;i < x;i++)
{
Grid::Cells[i] = (int*)malloc(y*s);
}
SetPalette(1, 255, 255, 255, 0);
}
void Grid::DrawGrid(SDL_Renderer* renderer)
{
std::cout << Grid::palette[Cells[i][o]].r << " : " << Cells[i][o];
SDL_SetRenderDrawColor(renderer, palette[Cells[i][o]].r, palette[Cells[i][o]].g, palette[Cells[i][o]].b, palette[Cells[i][o]].a);
SDL_RenderDrawPoint(renderer, i, o);
}
void Grid::SetPalette(int c, int r, int g, int b, int a)
{
palette[c].r = r;
我也有绿色,蓝色和alpha}
表示表达式必须具有类类型。我该如何修复我已经努力想弄明白了。所以我希望我至少能得到一个答案
我删除了一些不相关的代码,这样就不会占用太多的空间
您没有为调色板元素分配内存。如果不修改数据布局(这很糟糕,见下文),您至少需要在构造函数中分配元素(在SetPalette
之前):
for(int i = 0; i != 255; i++) {
palette[i] = new SDL_Color;
}
(你还需要释放这些内存,例如在destructor中)。
当调色板声明为SDL_Color* palette[255];
时,表达式palette[c]
具有SDL_Color*
类型。使用.
操作符访问结构字段需要结构,而不是指针-因此直接解决方案是palette[c]->r
(或手动解引用并使用.
,但这正是->
所做的)。
然而,分配这么多这么小的对象的成本相对较高,在给定的示例中没有必要这样做。如果您的调色板大小是恒定的(因为它是),您可以使用SDL_Color palette[255]
并删除所有分配/释放代码(并且不需要->
,因为palette[c]
的类型现在是SDL_Color
)。如果大小在编译时不知道-你可以用单个分配(malloc
或new[]
)来分配颜色数组。如果大小在运行时发生变化,使用vector
可能更容易。
相关文章:
- 使用不带参数的函数访问结构元素
- 我想访问std::unique_ptr中的一个特定元素
- 访问类lintalizer列表中的结构元素
- 从C++中的对列表中访问特定元素
- 访问动态分配列表中的元素
- 如何从静态向量访问类元素?
- 以C++访问矢量中的地图元素
- 映射基于自动的循环单元素访问C++
- 用元组作为C 的元素访问元组
- 元素访问(获取和放置)在C++中使用 std::vector
- 在Haskell中使用O(1)元素访问实现高效的类似拉链的数据结构
- std::map - 无异常且无需插入的元素访问
- C++2D矢量声明和来自调试器的元素访问
- 迭代器性能的重点应该放在高级还是元素访问上
- groot集合-元素访问
- 矩阵元素访问
- 对于boost::hana::tuple,元素访问的时间复杂度是多少?
- c++向量元素访问
- 通用容器和可变元素访问
- std::vector中的每个元素访问都是缓存未命中吗