c++ - 成员函数无法访问 C++ 私有成员变量
问题描述
我正在重新创建 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 来访问它(失败,因为它必须参考一个具体的例子)。有人知道我做错了什么吗?谢谢。
解决方案
在定义中,您没有指出 thatdrawPaddle
是 的成员Paddle
,因此它将该定义视为自由函数的定义,而不是成员函数。免费函数将无法访问私有成员。
它应该从
void Paddle::drawPaddle(Graphics gfx)
推荐阅读
- hugo - 如何在 HUGO 中获取 {{.GitInfo}}?
- python - 如何通过机器学习识别句子中的某些单词?
- vb.net - 如何在发送之前在我的 pdf 中设置密码?
- javascript - 三星互联网浏览器上的全屏高度不一致
- java - 将 assets 文件夹中的自定义 gif 加载到 recyclerview android
- java - 如何使用 jhipster 在 Kafka 集群上设置多个代理
- python - 如何使用 json 文件中的“时间戳”将 DataFrame 设置为从 X 日到 Y 日,而不是从 X 年到 Y 年?
- android - 如何在列表视图中将搜索结果显示为 SearchView 的下拉列表?
- python-3.x - 在 tkinter GUI 中更新温度读数
- html - 如何固定表头的位置并仅滚动表体