[C ++共享全局变量而不使用外部变量的最佳方法?

问题描述 投票:0回答:2

所以,我想要有一个global.h文件,其中包含供其他类/函数使用的变量/函数。例如,假设我有三个头文件:global.h,local1.h和local2.h。在这里,local1.h和local2.h将使用global.h中的变量。但是,如果我在local1.h和local2.h中都包含global.h,则将导致多定义错误。我知道我们可以使用关键字“ extern”,但是我听说它的做法不好,所以我试图避免这种情况。

我试图通过使用类来解决这个问题。基本上,我有一个包含所有静态变量的基类。这样,任何将使用这些变量的类都可以从基类继承。 (就我而言,我很好,因为我的大多数程序都是由类组成的)。下面是代码,

Base.h

class base{
    static const int SCREEN_SIZE = 1000;
};

class1.h

#include "base.h"
class class1: public base{
    void printSize(){
        cout << SCREEN_SIZE << endl;
    }
};

class2.h

#include "base.h"
class class2: public base{
    int getSize(){
        return SCREEN_SIZE;
    }
};

但是我不确定这是否是最好的方法,有什么建议吗?

这是我的实际代码:

#ifndef GAME_CORE_H
#define GAME_CORE_H

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <stdio.h>

namespace Colors{
const SDL_Color RED = {255, 0, 0, 255};
const SDL_Color GREEN = {0, 255, 0, 255};
const SDL_Color BLUE = {0, 0, 255, 255};
const SDL_Color YELLOW = {255, 255, 0, 255};
const SDL_Color PURPLE = {128, 0, 128, 0};
const SDL_Color ORANGE = {255, 68, 0, 255};
const SDL_Color WHITE = {255, 255, 255, 255};
const SDL_Color BLACK = {0, 0, 0, 255};
};

namespace GAME_CORE{
SDL_Window* gWindow = NULL;
SDL_Renderer* gRenderer = NULL;
SDL_Surface* gWindowSurface = NULL;
TTF_Font* defaultFont = NULL;

const int SCREEN_INIT_WIDTH = 1280;
const int SCREEN_INIT_HEIGHT = 720;
const int TILESIZE = 32;

void CORE_Init();
};


#endif // GAME_CORE_H

所以错误消息显示了多个定义gWindow,gRenderer,gWidowSurface和defaultFont

c++ global
2个回答
0
投票

我建议.h文件应用于原型,而不是实际上不声明任何类型或函数的声明:

内联变量/函数静态变量/函数const变量使用int = Reg; typedef Reg int;

我希望您通过两个选项实现它

var.h
class var{
   public:
    var()=default;

  private:
     int _list {};

    operator +(int); //prototypes

};



var.cpp
//Then u can implement the declaration like
   #include"var.h"
    class var{
    //Implement it here

   };

或者您也可以像标准库那样在没有扩展名的文件中声明完整的类。

这里是可以生成这些文件的C程序

int main (void){
   FILE* ptr = fopen ("vector","w+");
}

0
投票

使用标题保护。

例如

Base.h

#ifndef base_h
#define base_h
class base{
    static const int SCREEN_SIZE = 1000;
};
#endif
© www.soinside.com 2019 - 2024. All rights reserved.