简体   繁体   English

指向成员函数的C ++指针

[英]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. &Object::foo接受成员函数的地址,为您提供一个指向成员函数的指针。 It's type is int (Object::*)(int*) , so the type of p1 has to match. 它的类型是int (Object::*)(int*) ,所以p1的类型必须匹配。

  2. *Object::foo attempts to perform indirection on the member function, which is simply not something you can do. *Object::foo尝试对成员函数执行间接操作,这根本不是您可以做的。 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. 请注意,您为p2提供的类型是对成员函数指针的引用,因此不会绑定到临时函数。 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: 要处理对成员函数指针的引用,最简单的方法是引入适当的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);
}

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. 当我尝试编写和改进此答案时,我还ObjFPtrTypeRef了一个事实,即ObjFPtrTypeRef不等同于ObjFPtrType& ,而是形成了它自己的类型。
The above sample compiles fine and was proven with GCC 4.8.2 on ideone . 上面的样品编译良好,并在亚酮上GCC 4.8.2进行了证明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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