Polymorphism: “A pointer to a bound function may only be used to call the function”

隐身守侯 提交于 2019-12-11 07:41:44

问题


I'm separating my code into multiple files, but this is one thing I don't get.

In graphics.h:

...
class graphics {
public:
virtual void SizeMod(int w, int h);
...
}

In graphics.cpp:

...
void SizeMod(int w, int h) {
    //Code here.
}
...

In main.cpp:

...
graphics g;
...
int main (int argc, char **argv) {
    ...
    glutReshapeFunc(g.SizeMod);
    ...
}

Error:

error C3867: 'graphics::SizeMod': function call missing argument list; use &graphics::SizeMod to create a pointer to member

And so I did that:

...
graphics g;
...
int main (int argc, char **argv) {
    ...
    glutReshapeFunc(&graphics::SizeMod);
    ...
}

It still gives me an error (a different one). Anything to solve this problem?


回答1:


it won't work this way because SizeMod is a non-static class member method, so it needs this to be called on. You have to make SizeMod static.




回答2:


GLUT is a C API. glutReshapeFunction expects a callback to a function of the signature

void (int, int)

A C++ class member function, in your case graphics::SizeMod has the signature

graphics::void(int, int)

Now, there's no well defined C++ ABI that could be strictly translated into the commonplace C ABI, but for all practical means on most compilers the C++ signature from above looks like

void(graphics*, int, int)

if looked through the glasses of a C ABI.

This first graphics* parameter that's the implicit this pointer.

Which essentially means, when you pass that as callback to glutReshapeFunction it breaks because

  • the types don't match
  • and there's no way to somehow pass the instance along

EDIT: C++ lambdas don't work here as pointed out by Mike Dinsdale.


Seriously, I'm really getting sick and tired of answering same question again, and again, and again, and again… It get's asked about 3 times a week.



来源:https://stackoverflow.com/questions/18652267/polymorphism-a-pointer-to-a-bound-function-may-only-be-used-to-call-the-functi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!