简体   繁体   English

如何调用成员函数指针?

[英]How do I call a pointer-to-member-function?

I'm getting a compile error (MS VS 2008) that I just don't understand. 我收到一个我不明白的编译错误(MS VS 2008)。 After messing with it for many hours, it's all blurry and I feel like there's something very obvious (and very stupid) that I'm missing. 弄乱了好几个小时之后,一切都变得模糊了,我觉得我很想念(很愚蠢)。 Here's the essential code: 这是基本代码:

typedef int (C::*PFN)(int);

struct MAP_ENTRY
    {
    int id;
    PFN pfn;
    };

class C
    {
    ...
    int Dispatch(int, int);
    MAP_ENTRY *pMap;
    ...
    };

int C::Dispatch(int id, int val)
    {
    for (MAP_ENTRY *p = pMap; p->id != 0; ++p)
        {
        if (p->id == id)
            return p->pfn(val);  // <--- error here
        }
    return 0;
    }

The compiler claims at the arrow that the "term does not evaluate to a function taking 1 argument". 编译器在箭头处声明“该项不等于带有1个参数的函数”。 Why not? 为什么不? PFN is prototyped as a function taking one argument, and MAP_ENTRY.pfn is a PFN. PFN被原型化为带有一个参数的函数,而MAP_ENTRY.pfn是PFN。 What am I missing here? 我在这里想念什么?

p->pfn is a pointer of pointer-to-member-function type. p->pfn是指向成员函数类型的指针。 In order to call a function through such a pointer you need to use either operator ->* or operator .* and supply an object of type C as the left operand. 为了通过这样的指针调用函数,您需要使用operator- ->*或operator .*并提供C类型的对象作为左操作数。 You didn't. 你没有

I don't know which object of type C is supposed to be used here - only you know that - but in your example it could be *this . 我不知道应该在这里使用哪个C类型的对象-只有您知道-但在您的示例中可能是 *this In that case the call might look as follows 在这种情况下,呼叫可能如下所示

(this->*p->pfn)(val)

In order to make it look a bit less convoluted, you can introduce an intermediate variable 为了使它看起来更容易混淆,您可以引入一个中间变量

PFN pfn = p->pfn;
(this->*pfn)(val);

尝试

return (this->*p->pfn)(val);

Just to chime in with my own experience, I've come across an error in g++ caused by this statement: 只是为了亲身体验,我遇到了由以下语句引起的g ++错误:

  (this -> *stateHandler)() ;

Where stateHandler is a pointer to a void member function of the class referenced by *this. 其中stateHandler是指向* this引用的类的void成员函数的指针。 The problem was caused by the spaces between the arrow operator. 该问题是由箭头运算符之间的空格引起的。 The following snippet compiles fine: 以下代码片段可以正常编译:

(this->*stateHandler)() ;

I'm using g++ (GCC) 4.4.2 20090825 (prerelease). 我正在使用g ++(GCC)4.4.2 20090825(预发行版)。 FWIW. FWIW。

p->pfn is a function pointer. p-> pfn是一个函数指针。 You need to use * to make it function. 您需要使用*使其起作用。 Change to 改成

(*(p->pfn))(val)

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

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