无法调用指向成员函数的指针

时间:2022-11-10 16:46:06

I'm trying to call a function pointer that points to a member function and I either get the error

我正在尝试调用指向成员函数的函数指针,我得到错误

Error 3 error C2064: term does not evaluate to a function taking 0 arguments

错误3错误C2064:term不计算为采用0参数的函数

or

Error 3 error C2171: '*' : illegal on operands of type 'Foo::func_t

错误3错误C2171:'*':在类型为'Foo :: func_t的操作数上非法

my code looks like

我的代码看起来像

class Foo
{
   void stuff();
   void more_stuff();
   void my_func();

   typedef void(Foo::* func_t)(void);
   func_t fptr;
};

void Foo::my_func()
{
   //do some stuff
}

void Foo::stuff()
{
   fptr = &Foo::my_func;
}

void Foo::more_stuff()
{
   if(fptr != 0)
   {
       (*fptr)(); //error C2171: '*' : illegal on operands of type 'Foo::func_t
       (fptr)(); //term does not evaluate to a function taking 0 arguments
   }
}

Can anyone see the issue here?

谁能在这里看到这个问题?

1 个解决方案

#1


The correct syntax is

正确的语法是

(this->*fptr)();

This is required since it's a member function pointer and you need to explicitly provide an instance to work on when using fptr. It might look like the compiler could already use the implicit *this, but that is not what the standard says and hence you need to take care of it manually.

这是必需的,因为它是一个成员函数指针,你需要在使用fptr时显式提供一个实例。可能看起来编译器已经可以使用隐式* this,但这不是标准所说的,因此您需要手动处理它。

#1


The correct syntax is

正确的语法是

(this->*fptr)();

This is required since it's a member function pointer and you need to explicitly provide an instance to work on when using fptr. It might look like the compiler could already use the implicit *this, but that is not what the standard says and hence you need to take care of it manually.

这是必需的,因为它是一个成员函数指针,你需要在使用fptr时显式提供一个实例。可能看起来编译器已经可以使用隐式* this,但这不是标准所说的,因此您需要手动处理它。