CPP 私有数据成员SDL_Rect非活动状态

cpp private data member SDL_Rect inactive

本文关键字:Rect 活动状态 SDL 数据成员 CPP      更新时间:2023-10-16

我有一个 7 x 7 的探头矩阵,它传递的信号代表在被调查区域中该点测量的水平。 我可以在 SDL 中绘制 7 x 7 矩形的矩阵,但无法更新颜色。
我有一堂课类探针 { 公共: 探针(); ~探测器(); void SetColor(int x); void Set_id(int x, int y, int z);
无效Level_id(无效);

private: 
    int OldColor; 
    int Xcord; 
    int Ycord; 
    SDL_Rect rect; //This does not keep the rect that I create?
};
//outside all curly brackets {} I have 
Probe Level[7][7];
//I initialize each instance of my class 
Level[x][y].Set_id(x, y, z); and I use x and y to create and position the rectangle
//  Defininlg rectangles
    SDL_Rect rect = {BLOCK_W * Xcord, BLOCK_H * Ycord, BLOCK_W, BLOCK_H};
/*I get what I expected, by the way z sets the color and it is incremented so each rectangle has a      different color. */
//I used function SetColor, it failed untill I regenerated rect
//in the SetColor function.  I have
private:
SDL_Rect rect;
//It is private why do I need to re-create the SDL_Rect rect?
//Why is it not stored like 
private:
int Xcord; // !!?  Regards Ian.
如果我

理解正确,你的类看起来像这样:

class Probe {
public:
   Probe();
   ~Probe();
   void SetColor(int x);
   void Set_id(int x, int y, int z) {
      SDL_Rect rect = {BLOCK_W * Xcord, BLOCK_H * Ycord, BLOCK_W, BLOCK_H};
   }
private:
   int OldColor; 
   int Xcord; 
   int Ycord; 
   SDL_Rect rect;
};

您想知道为什么"rect"变量不会另存为私有变量,以及在绘制SDL_Rect时如何更改颜色?

首先,你的"rect"没有被保存,因为你在函数中定义了一个新的"rect"变量。您应该做的是以下任一操作:

rect = {BLOCK_W * Xcord, BLOCK_H * Ycord, BLOCK_W, BLOCK_H};

rect.x = BLOCK_W * Xcord;
rect.y = BLOCK_H * Ycord;
rect.w = BLOCK_W;
rect.h = BLOCK_H;

要更改渲染的颜色(假设您使用的是 SDL_RenderDrawRect 函数,因为这是我所知道的唯一一个可以绘制SDL_Rects函数),您只需调用:

SDL_SetRenderDrawColor(int r, int g, int b, int a);

就在调用 SDL_RenderDrawRect 函数之前(每次)。如果不这样做,并在其他位置调用 SetRenderDrawColor 函数,则颜色将更改为该颜色。