如何在不创建类实例的情况下使用成员函数,使用std :: function?

Mat*_*ock 1 c++ class function c++11

我正在寻找一种在不创建类实例的情况下调用成员函数的方法,我不是指静态函数.

情况如下:

//Texture.cpp
#include "Window.hpp"//Window included
void Texture::Init(const char* path, const Window&)
{
  loadTexture(path, Window.getRenderer();
}

void Texture::loadTexture(const char* path, SDL_Renderer* renderer)
{
  //code...
}
Run Code Online (Sandbox Code Playgroud)

Window有一个成员函数SDL_Renderer*getRenderer().但是,我不能在这种情况下使用它,因为没有创建Window的实例.

我遇到了这个问题,如果我必须自己找到一个方法,我会做同样的事情:创建静态函数.但是,这看起来像是为我解决了一个问题.使用std :: function和std :: bind的答案看起来不错,但我无法弄清楚如何使用它.有人可以帮帮我吗?

我有:

  • 函数loadTexture,将const char*和SDL_Renderer*作为参数,并返回void
  • 函数Init,将const char*和const Window&作为参数,并返回void
  • class Window,它具有函数getRenderer,不带参数并返回SDL_Renderer*

请问有人帮我解释一下,所以下次遇到这个问题时我可以自己做同样的事吗?

提前致谢.

nul*_*ptr 6

没有实例就不能执行非静态方法(std :: function和其他任何东西都不允许这样做).

通常,非静态方法访问某些实例数据.您必须提供这些数据(即实例).

在你的情况下,我认为渲染器必须知道它渲染的窗口.

但是为什么你想在没有实例的情况下调用getRenderer?你有一个实例:const Window&是一个实例.所以只需使用第二个参数:

void Texture::Init(const char* path, const Window& wnd)
{
  loadTexture(path, wnd.getRenderer());
}
Run Code Online (Sandbox Code Playgroud)