简体   繁体   中英

Global Variables Class c++

First question here, and answer is probably very simple, but i can't figure it out. To the point: In my project i created 2 classes: "GlobalVairables" and "SDLFunctions". Obviously, in first one i want to store globals which i could relate to in any other class, and in the second on i got few functions using those globals. Here's code:

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;
};

and 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)
{
}

and here is one function in SDLFunction.cpp, that uses "gWindow" and 2 other variables:

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

My problem is, that on debugging, i get

error C2065: 'gWindow' : undeclared indentifier

Of course, in SDLFunctions.cpp i got "#include "GlobalVariables.h" ". Also, those variables are public, so it's not this (probably). Can someone tell what's wrong? Is there some simple solution, or do i have to reorganize it, and shouldn't use globals? Please help.

First of all, your variables are members of every instance of the class, and as such, are not globals in usual meaning. You might want to declare them static. What is even better, do not create a class for them at all - instead, put them into namespace. Something like following (in your .h file):

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

Than you can reference them in your code in a following manner:

int dot = globals::SCREEN_WIDTH;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM