将函数 ptr 获取到实例化类的成员函数?
class gfx {
void resize(int x, int y);
}
gfx g;
我可以以某种方式将 g.resize 转换为 'void (*)(int, int)' 吗?
class gfx {
void resize(int x, int y);
}
gfx g;
can i cast g.resize to a 'void (*)(int, int)' somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不。
gfx::resize
的类型为void(gfx::*)(int, int)
。您无法将其有意义地转换为void(*)(int, int)
类型,因为您只能将其作为gfx
类型的对象上的成员函数进行调用。成员函数只能在类的实例上调用,因此给定您的
gfx g;
,您可以调用g.resize()
,但您不能仅仅像调用普通函数一样调用resize()
。普通函数指针不能指向成员函数,因为它没有任何方法将函数调用绑定到类的实例。从概念上讲,成员函数需要一个附加参数,即
this
参数,该参数指向调用它的类的实例。如果您希望能够通过普通函数指针调用成员函数,则可以创建一个带有参数的非成员函数(或静态成员函数)包装器,您可以向该参数传递要调用该成员的对象的实例功能。例如,您可以:
此非成员
resize
函数的类型为void(*)(gfx*, int, int)
并且可以作为非成员函数进行调用。这种方法的通用形式是 C++0x 中的std::function
和std::bind
设施(您也可以在 Boost 和 C++ TR1)。No.
gfx::resize
is of typevoid(gfx::*)(int, int)
. You can't meaningfully convert it to typevoid(*)(int, int)
because you can only call it as a member function on an object of typegfx
.A member function can only be called on an instance of the class, so given your
gfx g;
, you can callg.resize()
, but you can't just callresize()
like it were an ordinary function. An ordinary function pointer can't point to a member function because it doesn't have any way to bind the function call to an instance of the class.Conceptually, a member function takes an additional parameter, the
this
parameter, that points to the instance of the class on which it was called.If you want to be able to call a member function via an ordinary function pointer, you can create a nonmember function (or a static member function) wrapper with a parameter to which you can pass the instance of the object on which to call the member function. For example, you could have:
This nonmember
resize
function has typevoid(*)(gfx*, int, int)
and can be called as a nonmember function. The generalized form of this approach is thestd::function
andstd::bind
facilities found in C++0x (you can also find them in Boost and in C++ TR1).是的,你可以这样做:
Yes, you can do it: