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

编程入门 行业动态 更新时间:2024-10-10 00:26:50
本文介绍了如何传递一个类方法作为另一个函数的参数在C ++和OpenGL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道这个事情是有效的:

I know this thing works:

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

所以我试图将myDisplay()函数包含在一个类中。因为我想在将来用不同的类重载它。但是,编译器抱怨说,类型为'void(ClassBlah ::)()'的参数不匹配'void(*)()'的参数,

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

'。

这是我尝试做的:

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

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

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

推荐答案

首先,在非静态成员函数中有一个隐含的this指针,将 ClassBlah 中的 void myDisplay()更改为静态。解决这个限制是很尴尬的,这就是为什么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.

根据您的重载动机(例如,您是否要在运行时或在编译时间执行热交换实现),您可以考虑使用实用程序handler静态类,它包含一个指向你的基类的指针,并通过该类指定责任。

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?

本文发布于:2023-10-12 16:23:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485261.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数   方法   OpenGL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!