我正在重新创建pong,并且在将drawPaddle函数从Game主类移至Paddle类时,遇到了一个问题,即该函数无法读取成员变量(即使它们在同一类中)。该类在头文件中,而函数定义在cpp文件中。有问题的变量是高度,宽度,xPos和yPos。
桨类
#include "Graphics.h"
class Paddle
{
public:
void setX(int z)
{
xPos = z;
}
int getX()
{
return xPos;
}
void setY(int z)
{
yPos = z;
}
int getY()
{
return yPos;
}
int getWidth() {
return width;
}
void setHeight(int z)
{
height = z;
}
int getHeight()
{
return height;
}
void setPlayer(bool z)
{
player = z;
}
bool getPlayer()
{
return player;
}
private:
//functions
void drawPaddle(Graphics& gfx);
void updatePaddle(Graphics& gfx);
//variables
int xPos;
int yPos = Graphics::ScreenHeight / 2 - Paddle::height / 2;
bool player;
static constexpr int width = 20;
int height = 100;
};
drawPaddle函数
#include "Paddle.h"
#include "Graphics.h"
void drawPaddle(Graphics gfx)
{
for (int i = 0; i < width; i++)
{
for (int j = 0; j < Paddle::height; j++)
{
gfx.PutPixel(p.getX() + i, p.getY() + j, Colors::White);
}
}
}
如您所见,我尝试使用原始变量(告诉我变量未定义),通过类(告诉我变量不可访问)并使用getter对其进行访问(失败,因为它必须引用到)特定实例)。有人知道我在做什么错吗?谢谢。
In the definition, you didn't indicate that
drawPaddle
was a member ofPaddle
, so it was treating that definition as a definition of a free function, not a member function. Free functions wouldn't have access to the private members.It should start with
void Paddle::drawPaddle(Graphics gfx)