无法从构造函数访问私有变量 - 不在范围(C )中

Cannot access private variable from constructor - not in scope (C++)

本文关键字:范围 变量 构造函数 访问      更新时间:2023-10-16

我正在在SDL2中创建一个简单的游戏并学习C 类,但是我在私人变量和类构造函数方面遇到了困难。我正在尝试访问定义为私有变量并在构造函数中修改的SDL_Texture

编译后,以下代码导致以下错误:

In constructor 'PlayerShip::PlayerShip(SDL_Texture*)': |5| error: 'ShipSprite' was not declared in this scope

标题文件(Playershers.H):

#ifndef PLAYERSHIP_H
#define PLAYERSHIP_H
#include "SDL2/SDL.h"
class PlayerShip
{
    public:
        PlayerShip(SDL_Texture * tex);
    private:
        SDL_Texture * ShipSprite = nullptr; //The variable/texture I want to modify
};
#endif

cpp文件(playership.cpp)

#include "PlayerShip.h"
PlayerShip::PlayerShip(SDL_Texture * tex) //ctor
{
    ShipSprite = tex; //This needs to change the private variable above. However "ShipSprite" is apparently not in scope.
}

它是在标题中定义的,但是我不确定即使它在班级内部,它也不会访问它。我已经尝试搜索解决此问题的解决方案,但是我发现的解决方案与我的问题无关。

最重要的是,我尝试将ShipSprite = tex;更改为以下内容,但没有成功: PlayerShip::ShipSprite = tex;this->ShipSprite = tex;

对此的任何想法将不胜感激。谢谢。

取决于您的编译器的最新情况,它可能不接受没有整数类型的非静态成员的初始化。或者它可能不知道关键字nullptr

SDL_Texture * ShipSprite = nullptr;

尝试

SDL_Texture * ShipSprite;

查看是否不定义其他地方的guard( #ifndef PLAYERSHIP_H)。

另外,检查mingw的输出,它使用的哪些文件,也许您的假设是错误的?您还可以进行快速而肮脏的调试,例如在标题文件中引入语法错误。如果未捕获,甚至没有使用该文件。

除此之外,我建议其他一些事情(与您的问题无关):

  • 具有与班级名称不同的成员变量的命名约定。Shipsprite可以是Shipsprite_,m_shipsprite,shipsprite或您有什么。(一组很好的建议:http://geosoft.no/development/cppstyle.html)

  • 如果要初始化成员变量,则希望使用constructor Initializer列表进行。IE。: PlayerShip::PlayerShip(SDL_Texture * tex) : ShipSprite(tex) { }如果您想做的事情更精确,则编译器可能会更有帮助。

在添加变量之前,我可能会分别汇总了标头文件,并且它将PlayerShip.gch文件与我的标题放在同一文件夹中。海湾合作委员会可能尝试使用它而不是普通标头文件,从而给了我这个错误。

尽管如此,删除.gch文件似乎已经解决了我的问题,现在该程序正确编译了。不知道我是如何完全错过的。

再次感谢大家的建议和帮助。

编辑:我该如何关闭?