我有一个名为 Engine 的类。 类 TextureManager 的对象在类 Engine 以及类 Window 的内部。
我的问题是 TextureManager 内部的函数无法访问类 Window 内部的公共(public)函数或变量。
这是 C++ 的预期功能吗?还是您认为我错误地声明/定义了一个或两个这些对象。
如您所见,在引擎内部有一个 TextureManager 和一个 Window。
class Engine
{
public:
Engine();
~Engine();
Window gameWindow;
TextureManager textures;
SDL_Event event;
int test;
};
这是类 Window 的标题
class Window
{
public:
//Constructors
Window();
~Window();
//Getter Functions
SDL_Surface * get_screen();
//Other Functions
void toggle_fullscreen();
void render();
void initialize(int screenwidth, int screenheight);
bool handle_events(SDL_Event event);
bool check_error();
private:
bool windowed;
bool windowFailure;
int screenWidth;
int screenHeight;
SDL_Surface * screen;
};
这是TextureManager类的头文件
class TextureManager
{
public:
TextureManager();
~TextureManager();
int new_texture(std::string filename);
int new_section(int indexOfTexture, int x, int y, int width, int height);
void render_texture(int textureID, int x, int y);
void render_section(int textureSectionID, int x, int y);
private:
std::vector< Texture > textureIDs;
std::vector< TextureSection > textureSectionIDs;
};
这是我遇到问题的功能。在函数调用 SDL_BlitSurface() 中访问 gameWindow 时出现错误
void TextureManager::render_texture(int textureID, int x, int y)
{
SDL_Rect coordinates;
coordinates.x = x;
coordinates.y = y;
SDL_BlitSurface(textureIDs[textureID].get_texture(), NULL, gameWindow.get_screen(), &coordinates);
}
最佳答案
如前所述,TextureManager 实例不知道类 Window 的 gameWindow 实例。您可以考虑使用以下方法来允许 TextureManager 与 gameWindow 交互:
class TextureManager {
public:
TextureManager(Window& w) : m_refWindow(w) { /*...*/ }
/*...*/
protected:
Window& m_refWindow;
/*...*/
}
void TextureManager::SomeMethod()
{
m_refWindow.DoSomething();
}
Engine::Engine() :
gameWindow(),
textures(gameWindow)
{
/*...*/
}
这样,textures
对象将绑定(bind)到 gameWindow
对象,并且能够调用其公共(public)函数。`
关于c++ - 关于两个类的范围的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8584004/