如何在 C++ 和 openGL 中将类方法作为另一个函数的参数传递?

2021-12-19 00:00:00 opengl methods c++ glut

我知道这东西有效:

void myDisplay()
{
...
}
int main()
{
...
glutDisplayFunc(myDisplay)
...
}

所以我尝试将 myDisplay() 函数包含到我创建的类中.因为我想将来用不同的类重载它.但是,编译器抱怨

so I tried to include myDisplay() function to a class that I made. Because I want to overload it in the future with a different class. However, the compiler complains that

'void (ClassBlah::)()' 类型的参数与 'void(*)()' 不匹配.

这是我尝试制作的内容:

Here is the what I try to make:

class ClassBlah
{
   ....
   void myDisplay()
   ....
}
......
int main()
{

    ...
    ClassBlah blah
    glutDisplayFunc(blah.myDisplay)
    ...
}

有人知道如何解决这个问题吗?非常感谢.

Does anybody knows how to fix this problem? Many thanks.

推荐答案

首先,在非静态成员函数中有一个隐式的this"指针,所以你需要改变你的void myDisplay()<ClassBlah 中的/code> 是静态的.解决这个限制很尴尬,这就是为什么 C++ faq lite 说 不要这样做

Firstly, there is an implicit "this" pointer in non-static member functions, so you'll need to change your void myDisplay() in ClassBlah to be static. It's awkward to work around this limitation, which is why the C++ faq lite says don't do it

然后,您应该可以将函数作为 ClassBlah::myDisplay 传递.

Then, you should be able to pass the functions as ClassBlah::myDisplay.

根据您重载的动机(即您是要在运行时热交换进出实现,还是仅在编译时?)您可能会考虑一个实用程序处理程序"静态类,其中包含指向您的基类的指针,并且通过这种方式委派责任.

Depending on your motivation for overloading (ie are you going to hotswap implementations in and out at runtime, or only at compile time?) you might consider a utility "handler" static class that contains a pointer to your base class, and delegates responsibility through that.

相关文章