全局变量 Class c++

Global Variables Class c++

这里是第一个问题,答案可能很简单,但我想不出来。关键点: 在我的项目中,我创建了 2 个 classes:"GlobalVairables" 和 "SDLFunctions"。 显然,在第一个中我想存储我可以在任何其他 class 中关联的全局变量,在第二个中我使用这些全局变量的函数很少。这是代码:

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"”。此外,这些变量是 public,所以不是这个(可能)。 有人能告诉我出了什么问题吗?是否有一些简单的解决方案,或者我是否必须重新组织它,并且不应该使用全局变量?请帮忙。

首先,您的变量是 class 每个实例的成员,因此,不是通常意义上的全局变量。您可能希望将它们声明为静态的。更好的是,根本不要为它们创建 class - 相反,将它们放入命名空间。类似于以下内容(在您的 .h 文件中):

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

您可以通过以下方式在您的代码中引用它们:

int dot = globals::SCREEN_WIDTH;