2011-05-05 50 views
0

我遇到了C++的麻煩。 我正在爲使用SDL處理圖形的遊戲製作引擎類。 引擎類是(希望正確實現)單例。錯誤:'screen'未在此範圍內聲明

engine.h

#ifndef H_ENGINE 
#define H_ENGINE 

#ifndef H_SDL 
#include "SDL/SDL.h" 
#endif 

class Engine { 
public: 
    static Engine *getInstance(); //This returns the singleton object of class 
    int init(int screenWidth, int screenHeight); //must initialize before use 
    ~Engine(); //destructor 

private: 
    Engine(); //private constructor 
    static Engine *instance; //stores the single instance of the class 
    SDL_Surface *screen; //Struct for SDL 
}; 

#endif 

engine.cpp

#include "engine.h" 

Engine *Engine::instance = NULL; 

Engine::Engine() { 
    screen = NULL; 
} 

Engine *Engine::getInstance() { 
if(instance == NULL) 
    instance = new Engine(); 

return instance; 
} 

int init(int screenWidth, int screenHeight) { 
SDL_Init(SDL_INIT_EVERYTHING); 

//This line has the error: error: ‘screen’ was not declared in this scope 
screen = SDL_SetVideoMode(screenWidth, screenHeight, 32, SDL_SWSURFACE); 

return 1; 
} 

Engine::~Engine() { 
SDL_Quit(); 
} 

main.cpp中:包含線

Engine::getInstance()->init(600, 400); 

任何幫助,將不勝感激

+0

Singletons = BAD。這是非常糟糕的。別。永遠。 – Puppy 2011-05-05 19:48:42

回答

6

你忘了把階級預選賽init

int Engine::init(int screenWidth, int screenHeight) 

隨時都在發生。

0

您定義init爲:

int init(int screenWidth, int screenHeight) { 

然而,這規定全球範圍內的功能(有沒有screen變量)。

相反,如果你寫:

int Engine::init(int screenWidth, int screenHeight) { 

您將定義類的功能。