全局变量类c++

Global Variables Class c++

本文关键字:c++ 全局变量      更新时间:2023-10-16

这里的第一个问题,答案可能很简单,但我想不通。切中要害:在我的项目中,我创建了两个类:"GlobalVairables"answers"SDLFunctions"。显然,在第一个类中,我想存储可以在任何其他类中关联的全局变量,在第二个类中我得到了一些使用这些全局变量的函数。这里的代码:

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"和其他两个变量:

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

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

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

然后你可以用以下方式在代码中引用它们:

int dot = globals::SCREEN_WIDTH;