2015-12-14 138 views
0

這裏的第一個問題,答案可能很簡單,但我無法弄清楚。點: 在我的項目中,我創建了2個類:「GlobalVairables」和「SDLFunctions」。 顯然,在第一個我想存儲我可以涉及任何其他類的全局變量,並在第二個我使用這些全局變量的函數。這裏是代碼:全局變量類C++

GlobalVariables.h

#pragma once 
class GlobalVariables 
{ 
public: 
GlobalVariables(void); 
~GlobalVariables(void); 

const int SCREEN_WIDTH; 
const int SCREEN_HEIGHT; 

//The window we'll be rendering to 
SDL_Window* gWindow; 

//The surface contained by the window 
SDL_Surface* gScreenSurface; 

//The image we will load and show on the screen 
SDL_Surface* gHelloWorld; 
}; 

和GlobalVariables.cpp

#include "GlobalVariables.h" 


GlobalVariables::GlobalVariables(void) 
{ 

const int GlobalVairables::SCREEN_WIDTH = 640; 
const int GlobalVariables::SCREEN_HEIGHT = 480; 

SDL_Window GlobalVairables:: gWindow = NULL; 

SDL_Surface GlobalVariables:: gScreenSurface = NULL; 

SDL_Surface GlobalVariables:: gHelloWorld = NULL; 
} 


GlobalVariables::~GlobalVariables(void) 
{ 
} 

,這裏是在SDLFunction.cpp一個功能,即使用 「gWindow」 等2個變量:

gWindow = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); 

我的問題是,在調試時,我得到

error C2065: 'gWindow' : undeclared indentifier 

當然,在SDLFunctions.cpp中我得到了「#include」GlobalVariables.h「」。另外,這些變量是公開的,所以它不是(可能)。 有人可以說出了什麼問題嗎?有一些簡單的解決方案,還是我必須重新組織它,而不應該使用全局變量?請幫忙。

+1

如何是那些變量的全局?如果將整行更改爲'gWindow = null;'它應該起作用。 – forkrul

+0

您似乎沒有創建該類的實例(可能應該是單例類或命名空間),而且您似乎錯誤地引用了標識符('GlobalVariables :: gWindow'而不是'gWindow' ) – UnholySheep

+0

@UnholySheep - 這就是Java的習慣用法:除非沒有,否則一切都是對象。你絕對正確的,這應該是一個靜態數據成員而不是類的命名空間。 –

回答

8

首先,您的變量是類的每個實例的成員,因此,它們不是通常意義上的全局變量。你可能想要聲明它們是靜態的。更好的是,不要爲它們創建一個類 - 而是將它們放入命名空間。喜歡的東西以下(在你的.h文件中):

namespace globals { 
    static const unsigned int SCREEN_WIDTH = 640; 
    static const unsigned int SCREEN_HEIGHT = 1024; 
} 

比你可以以下列方式引用它們在你的代碼:

int dot = globals::SCREEN_WIDTH;