C ++使对象全局化并可从其他类访问,而不会破坏编码实践

时间:2018-02-14 20:53:47

标签: c++ class object sdl

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

对不起,因为我觉得这个问题要么已经被问过,要么有一个非常简单的答案,我没有意识到。我尝试搜索这个网站和其他论坛但是,我要么没有正确地问这个问题,要么找不到工作答案而不必在纹理类中初始化对象。

感谢您的帮助,如果我对这个问题提出质疑,我很抱歉。

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

1 个答案:

答案 0 :(得分:0)

感谢大家给我的帮助和建议,我最后更改了代码,只是通过绘图函数传递对象,将参数添加到函数纹理绘图中,而不仅仅是使对象成为全局。

<强>更新 在更好地理解指针之后,我意识到我可以在类初始化期间传递一个指针。