對付引用成員函數指針的最簡單的方法是引入適當的typedef恕我直言:當我試圖寫
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);
}
和改進這個答案,我也偶然發現ObjFPtrTypeRef
不等於ObjFPtrType&
,但形成它自己的類型。
上面的示例編譯得很好,並通過GCC 4.8.2 on ideone驗證。
只有第二行? – chris
「第二行」 - 你的意思是'使用命名空間標準;'?行編號有點有用... –
抱歉,我的意思是int(Object :: *&p)(int *)= * Object :: foo行以及前一行。 – user3250551