简体   繁体   中英

How to assign a member function to a pointer to member function in C++

I'm trying to assign a member function to a pointer to a member function in C++, but I am getting an error. I have code like this:

#ifndef MY_CLASS_H
#define MY_CLASS_H

class MyClass {
    MyClass* (MyClass::*memPtr_) (ParamType);
public:
    void myFunction();
    void myFunction2();
    void myFunction3();

    MyClass& foo(ParamType var);
    MyClass& bar(ParamType var);
    MyClass& fooBar(ParamType var);
    ...
};

#endif

and...

void MyClass::myFunction() {
    memPtr_ = &MyClass::foo;

...

void MyClass::myFunction2() {
    memPtr_ = &MyClass::bar;

...

void MyClass::myFunction3() {
    memPtr_ = &MyClass::fooBar;

...

And on the lines

memPtr_ = &MyClass::foo;

and

memPtr_ = &MyClass::bar;

and

memPtr_ = &MyClass::fooBar;

when I compile - I get the error:

"cannot convert 'MyClass& (MyClass::*)(ParamType)'
to MyClass* (MyClass::*)(ParamType)' in assignment."

I've searched - but I can't seem to find the solution to this problem - what is the correct syntax to assign a member function to the pointer to member function 'memPtr_'?

Jrok is correct, and I fixed the problem. I simply changed:

MyClass* (MyClass::*memPtr_) (ParamType);

to...

MyClass& (MyClass::*memPtr_) (ParamType);

您不要使用没有()的函数名的地址,这就是指针。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM