全局变量类c++
Global Variables Class c++
这里的第一个问题,答案可能很简单,但我想不通。切中要害:在我的项目中,我创建了两个类:"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;
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 当vector是tje全局变量时,c++中vector的内存管理
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 内联函数中具有内部链接的全局变量
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局变量 多读取器 一个写入器多线程安全?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 不同作用域中的静态变量和全局变量
- C++ 在编译时具有函数计算全局变量
- 修改程序的入口点时未调用全局变量的构造函数
- 使用 std::ios_base::Init 正确初始化全局变量
- 为什么我的全局变量似乎没有变化?
- C ++程序如何返回我的数组或写入全局变量
- 为什么我的数组值与此处的全局变量不匹配?
- QT C++中对全局变量的未定义引用
- 跨多个类的全局变量而不会出现重定义错误?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- C++线程不检测全局变量更改
- 在 elf 文件中查找全局变量的位置
- 包括一个类来定义全局变量参数 c++ :(