简体   繁体   中英

C++ pointer to member function

#include<iostream>
using namespace std;

struct Object{
int foo(int *a){return 0;}
};

int main(){

int (Object::**p1)(int *) = &Object::foo;

int (Object::*&p2)(int *) = *Object::foo;

}

I've been trying to figure this out but I can't seem to get it debugged.

"invalid initialization" for the second line.

Both lines will not compile.

  1. &Object::foo takes the address of a member function, giving you a pointer to the member function. It's type is int (Object::*)(int*) , so the type of p1 has to match.

  2. *Object::foo attempts to perform indirection on the member function, which is simply not something you can do. Indirection is something you perform on pointers.

Note that the type you've given for p2 is a reference to a pointer to member function, so it will not bind to a temporary. You could, for example, do this instead:

int (Object::*p1)(int *) = &Object::foo;
int (Object::*&p2)(int *) = p1;

To deal with references to member function pointers the easiest way is to introduce an appropriate typedefs IMHO:

struct Object {
   int foo(int *a) { return 0; }
   int bar(int *a) { return 1; }
};

typedef int (Object::*ObjFPtrType)(int *);
typedef int (Object::*&ObjFPtrTypeRef)(int *);

void setFnPtr(ObjFPtrType* p) {
    *p = &Object::foo;
}

void setFnPtrRef(ObjFPtrTypeRef r) {
    r = &Object::bar;
}

int main() {

    ObjFPtrType p1 = 0;
    setFnPtr(&p1);

    ObjFPtrTypeRef p2 = p1;
    setFnPtrRef(p2);
}

While I was trying to write and improve this answer, I also stumbled over the fact that ObjFPtrTypeRef isn't equivalent to ObjFPtrType& , but forms it's own type.
The above sample compiles fine and was proven with GCC 4.8.2 on ideone .

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