将函数 ptr 获取到实例化类的成员函数?

发布于 2024-10-09 12:45:17 字数 137 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故事和酒 2024-10-16 12:45:17

不。gfx::resize 的类型为 void(gfx::*)(int, int)。您无法将其有意义地转换为 void(*)(int, int) 类型,因为您只能将其作为 gfx 类型的对象上的成员函数进行调用。

成员函数只能在类的实例上调用,因此给定您的 gfx g;,您可以调用 g.resize(),但您不能仅仅像调用普通函数一样调用 resize()。普通函数指针不能指向成员函数,因为它没有任何方法将函数调用绑定到类的实例。

从概念上讲,成员函数需要一个附加参数,即 this 参数,该参数指向调用它的类的实例。

如果您希望能够通过普通函数指针调用成员函数,则可以创建一个带有参数的非成员函数(或静态成员函数)包装器,您可以向该参数传递要调用该成员的对象的实例功能。例如,您可以:

void resize(gfx* obj, int x, int y) {
    return obj->resize(x, y);
}

此非成员 resize 函数的类型为 void(*)(gfx*, int, int) 并且可以作为非成员函数进行调用。这种方法的通用形式是 C++0x 中的 std::functionstd::bind 设施(您也可以在 Boost 和 C++ TR1)。

No. gfx::resize is of type void(gfx::*)(int, int). You can't meaningfully convert it to type void(*)(int, int) because you can only call it as a member function on an object of type gfx.

A member function can only be called on an instance of the class, so given your gfx g;, you can call g.resize(), but you can't just call resize() 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:

void resize(gfx* obj, int x, int y) {
    return obj->resize(x, y);
}

This nonmember resize function has type void(*)(gfx*, int, int) and can be called as a nonmember function. The generalized form of this approach is the std::function and std::bind facilities found in C++0x (you can also find them in Boost and in C++ TR1).

感性不性感 2024-10-16 12:45:17

是的,你可以这样做:

void easy_resize(int x, int y) { g.resize(x, y); }

Yes, you can do it:

void easy_resize(int x, int y) { g.resize(x, y); }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文