Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

c++ - Pass a member function as argument error: "reference to non-static member function must be called"

I am new to C++ and would like to know how can a member function of a class be passed to another function which takes a function pointer as a parameter. For the code I tried, I get the error of "reference to non-static member function must be called".

Edit: Making the function static would solve the issue but then I would not be able to access the variables defined in the class.

file.cpp:

#include "fooHdr.h"
class bar {
    void clbck() 
    {
       // Do something 
    }
    void init()
    {
        foo(clbck()); 
    }
};
fooHdr.h:
void foo(void (*hndlr)()); 
fooHdr.c
void foo(void (*hndlr)()) { };
question from:https://stackoverflow.com/questions/65925174/pass-a-member-function-as-argument-error-reference-to-non-static-member-functi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Member function pointers are different from normal function pointers. A normal function pointer looks like this:

void foo() {}

void (*Func)() = foo;    // Function pointer.

And a member function pointer looks like this:

class MemberTest {
public:
    void foo() {}
};

void (MemberTest::*Func)() = &MemberTest::foo;  // Member function pointer. Notice the '&' operator here.

int main()
{
    MemberTest test;
    (test.*Func)();    // This is how to call member function pointers.
}

Accordingly, for your problem there, you need to define it as a member function pointer and not like a normal function pointer:

void foo(void (bar::*hndlr)()); 

And when calling the foo() function, it must return the address of the member function:

void init()
{
    foo(&bar::clbck); 
}

But still, you can't call the function from foo() like this, as it doesn't have the current instance of the bar object. So we have to make another parameter which takes the pointer to the current object:

void foo(bar* pBar, void (bar::*hndlr)()); 
...
foo(this, &bar::clbck); 

So now, when calling the member function from foo(), you can do it like this:

(pBar->*hndlr)();

Note: Add a forward declaration on top of the function foo() or else the compiler might complain saying that bar is undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...