Casting/Changing 类型指向类型的指针 (SDL_Rect)

Casting/Changing type to pointer to type (SDL_Rect)

我正在尝试将 SDL_Rect 传递给 SDL_RenderCopy,它采用 SDL_Rect 的地址。我有 SDL_Rect 我正在尝试传递存储在 Shot.h 文件中我的私有 class(称为 "Shot")变量。

这一切都发生在Shot.cpp

我的做法:

SDL_RenderCopy(other args..., &Shot::rect)

然而 visual studio 抱怨

"argument of type SDL_Rect Shot::* is incompatible with param of type const SDL_Rect *"

我确实有点理解错误,但不太明白如何将 Shot::rect 转换为简单地址...

为了能够使用 &Shot::rectrect 需要成为 Shot class 的 static member

要将指针传递给 non-static 成员,可以使用以下方法:

Shot sh;
SDL_RenderCopy(other args..., &sh.rect);

否则将无法知道要使用哪个 rectShot 对象。


如果您想将 class 的成员传递给一个函数,该函数将需要知道它必须使用 class 的哪个对象。

因此您必须传递对象,您将从中使用 rect 作为参数的一部分:上例中的 &sh.rect

如果使用&Shot::rect,则不知道使用哪个对象,因此rect需要是静态成员。这样 class.

的所有对象只有一个 rect

例如class Shot有多个对象:

Shot sh1;
Shot sh2;

该函数需要知道使用哪个矩形:sh1.rectsh2.rect

如果 SDL_RenderCopy() 是从 class Shot 内部调用的(或者是一个成员函数),rect 可以像这样直接传递:

SDL_RenderCopy(other args..., &rect);

您无法获取 class 变量的地址,除非它是静态的。我假设您想创建一个 object of class Shot,然后获取其成员的地址。最优雅的方法是为此编写一个合适的方法。

class Shot {
protected:
    SDL_Rect rect;
public:
    SDL_Rect const *getRect(void) const { return ▭ }
};

那么你可以使用:

Shot *shot = new Shot;
SDL_RenderCopy(other args..., shot->getRect())