How to pass a class method as an argument for another function in C++ and openGL?(如何在 C++ 和 openGL 中将类方法作为另一个函数的参数传递?)
问题描述
我知道这东西有效:
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.
这篇关于如何在 C++ 和 openGL 中将类方法作为另一个函数的参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 和 openGL 中将类方法作为另一个函数的参数传递?


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01