我在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