C++ 在不破坏编码实践的情况下使对象成为全局对象并可从其他 类 访问

C++ Making a object global and accessible from other classes, without breaking coding practices

在尝试使用 SDL2 制作基本游戏引擎时,我创建了一个系统,其中创建了来自 class 世界的对象。稍后尝试从 class 纹理管理器使用该对象时,但是我的程序无法访问该对象。

我很抱歉,因为我觉得这个问题以前有人问过,或者有一个我没有意识到的非常简单的答案。我试着搜索这个网站和其他论坛,但是,我要么没有正确地问这个问题,要么在没有初始化纹理 class 中的对象的情况下找不到有效的答案。

谢谢你的帮助,如果我问的不好,我很抱歉。

Engine.cpp

#include "Engine.hpp"
#include "TextureManager.hpp"
#include "World.hpp"

World* world = new World(0,0);

void Engine::init(const char *title, int xPos, int yPos, int width, int height, bool fullScreen) {

    world = new World(0,0); 
}

World.cpp

#include "World.hpp"
#include "TextureManager.hpp"
#include <SDL2/SDL.h>

class World {
public:
    World(int x, int y);
    ~World();


    SDL_Rect CalculateToWorld( SDL_Rect dest);

private:

    int xPos;
    int yPos;
};

World::World(int x, int y) {

    xPos = x;
    yPos = y;
}
World::~World() {

}

SDL_Rect World::CalculateToWorld( SDL_Rect dest) {

    dest.x += xPos;
    dest.y += yPos;
    return dest;
}

TextureManager.cpp

#include "Engine.hpp"

class TextureManager {

public:
    static void Draw(SDL_Texture* tex, SDL_Rect src, SDL_Rect dest);

};
void TextureManager::Draw(SDL_Texture* tex, SDL_Rect src, SDL_Rect dest) {
    dest = world -> CalculateToWorld(dest);
    SDL_RenderCopy(Engine::renderer, tex, &src, &dest);
}

感谢大家给我的帮助和建议,我最终更改了代码,仅通过绘制函数传递对象,向函数纹理绘制对象添加一个参数,而不是仅仅使对象成为全局对象。


更新: 在对指针有了更好的理解后,我意识到我可以在 class.

的初始化期间传递一个指针