我已经编写了一个数组函数来在外部绘制 openGL 代码,而无需在每次创建新函数时都在 Windows 的主循环中添加该函数。
它工作正常,但是当我将它指向另一个类中的 public void 函数时,它说“必须调用对非静态成员函数的引用”。
代码:
int main(int argc, const char * argv[])
{
Window* win = new Window(800, 600, "3D Game Engine");
Game game;
win->draw[0] = a;
win->draw[1] = game.render;
win->MainLoop();
delete win;
}
绘图函数:
typedef void (*function_ptr)(int);
function_ptr *draw = (function_ptr*)malloc(sizeof(function_ptr));
有什么方法可以调用吗?
谢谢
最佳答案
您遇到的问题如下:
void (*function_ptr)(int);
是一个指向函数的指针,该函数的一个参数类型为 int
。
如果类中有这样的方法:
class exampleClass
{
public:
void example(int a);
};
C++ 编译器将在内部生成一个带有隐式this
参数的函数——就像这样:
void exampleClass@example(exampleClass *this, int a);
(大多数 C++ 编译器在这些函数的名称中使用非法字符,如 @
- 但这在这里无关紧要。)
因此,您通常不能将类方法分配给此类函数指针。您可以将 (exampleClass *,int)
类型的函数分配给 (int)
类型的函数指针。
为了避免这种情况,编译器通常根本不允许您在函数指针中存储类方法。
“完全”意味着编译器也不允许您使用正确内部类型的函数指针:
void (*function_ptr_2)(exampleClass *, int);
exampleClass y;
/* Not supported by the compiler although it is
* theoretically possible: */
function_ptr_2 x1 = exampleClass::example;
function_ptr_2 x2 = y.example;
不幸的是,我的 C++ 知识不够好,所以我无法告诉您 Angew 的解决方案 (std::function
) 是否有效以及如何工作。
关于c++ - 在数组函数指针中调用 void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43825170/