簡體   English   中英

無法弄清楚如何訪問這些元素

[英]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;
}

(您還需要釋放此內存,例如在析構函數中)。

調色板聲明為SDL_Color* palette[255]; , 表達式palette[c]類型為SDL_Color* 訪問結構字段. 運算符需要結構,而不是指針 - 所以直接的解決方案是palette[c]->r (或手動取消引用並使用. ,但這正是->所做的)。

然而,分配大量如此小的對象的成本相對較高,在給定的示例中,這樣做沒有意義。 如果您的調色板大小不變(按原樣),您可以只使用SDL_Color palette[255]並刪除所有分配/解除分配代碼(並且不需要->因為palette[c]類型現在是SDL_Color )。 如果在編譯時不知道大小 - 您可以使用單個分配( mallocnew[] )分配顏色數組。 如果大小在運行時發生變化,使用vector可能更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM