不知道如何访问这些元素

cant figure out how to acces these elements

这是我的header

#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 }

它说表达式必须有 class 类型。我该如何解决 我努力想弄明白。所以我希望我至少能得到答案

我确实删除了一些不相关的代码,所以不会花费太多space

您没有为调色板元素分配内存。在不修改数据布局的情况下(这是不好的,见下文),您至少需要在构造函数中分配元素(在 SetPalette 之前):

for(int i = 0; i != 255; i++) {
    palette[i] = new SDL_Color;
}

(您还需要释放此内存,例如在析构函数中)。

调色板声明为 SDL_Color* palette[255];,表达式 palette[c] 的类型为 SDL_Color*。使用 . 运算符访问结构字段需要结构,而不是指针 - 因此直接解决方案是 palette[c]->r(或手动解除引用并使用 .,但这正是 -> 所做的)。

然而,分配大量如此小的对象的成本相对较高,在给定的示例中,这样做没有意义。如果你的调色板大小是恒定的(因为它是)你可以只使用 SDL_Color palette[255] 并删除所有 allocation/deallocation 代码(并且不需要 -> 因为类型 palette[c]现在 SDL_Color)。如果在编译时不知道大小 - 您可以使用单个分配(mallocnew[])分配颜色数组。如果大小在运行时发生变化,使用 vector.

可能更容易