首页 > 解决方案 > 成员函数无法访问 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 来访问它(失败,因为它必须参考一个具体的例子)。有人知道我做错了什么吗?谢谢。

标签: c++private-membersmember-functionsmember-variables

解决方案


在定义中,您没有指出 thatdrawPaddle是 的成员Paddle,因此它将该定义视为自由函数的定义,而不是成员函数。免费函数将无法访问私有成员。

它应该从 void Paddle::drawPaddle(Graphics gfx)


推荐阅读