我在SDL2中创建了一个简单的游戏并学习了C++类,但是我在使用私有变量和类构造函数时遇到了困难。我试图访问定义为私有变量的SDL_Texture
,并在构造函数中对其进行修改。无法从构造函数访问私有变量 - 不在范围内(C++)
在汇编下面的代码将导致以下错误:
In constructor 'PlayerShip::PlayerShip(SDL_Texture*)': |5| error: 'ShipSprite' was not declared in this scope
头文件(PlayerShip.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;
的任何想法,将不胜感激。谢谢。
编译器给你带来的* only *错误吗? –
这听起来像你可能有多个文件名为'PlayerShip.h' –
@BenVoigt是的,这是我得到的唯一错误,我检查了重复的文件,找不到任何。 – iownall555