【问题标题】:Passing a pointer to a class member function as a parameter将指向类成员函数的指针作为参数传递
【发布时间】:2013-08-11 08:06:05
【问题描述】:

我编写了一个小程序,试图将指向类成员函数的指针传递给另一个函数。你能帮我吗,我哪里出错了..?

#include<iostream>
using namespace std;
class test{
public:
        typedef void (*callback_func_ptr)();
        callback_func_ptr cb_func;

        void get_pc();

        void set_cb_ptr(void * ptr);

        void call_cb_func();
};
void test::get_pc(){
         cout << "PC" << endl;
}
void test::set_cb_ptr( void *ptr){
        cb_func = (test::callback_func_ptr)ptr;
}
void test::call_cb_func(){
           cb_func();
}
int main(){
        test t1;
            t1.set_cb_ptr((void *)(&t1.get_pc));
        return 0;
}

当我尝试编译时出现以下错误。

error C2276: '&' : illegal operation on bound member function expression

【问题讨论】:

  • 我总觉得newty.de/fpt/index.html很有用。
  • 成员函数不是函数。你需要的类型是void (test::*)(void *)...
  • Kerrek SB 是对的。但是,如果您打算为不同的类和实例调用相同的成员,您应该考虑继承和虚拟...

标签: c++ function-pointers


【解决方案1】:

您不能将函数指针强制转换为void*。

如果你想让一个函数指针指向一个成员函数你必须声明类型为

ReturnType (ClassType::*)(ParameterTypes...)

此外,您不能声明指向绑定成员函数的函数指针,例如

func_ptr p = &t1.get_pc // Error

相反,您必须得到这样的地址:

func_ptr p = &test::get_pc // Ok, using class scope.

最后,当您调用指向成员函数的函数指针时,您必须使用该函数所属的类的实例来调用它。例如:

(this->*cb_func)(); // Call function via pointer to current instance.

这是应用了所有更改的完整示例:

#include <iostream>

class test {
public:
    typedef void (test::*callback_func_ptr)();
    callback_func_ptr cb_func;
    void get_pc();
    void set_cb_ptr(callback_func_ptr ptr);
    void call_cb_func();
};

void test::get_pc() {
    std::cout << "PC" << std::endl;
}

void test::set_cb_ptr(callback_func_ptr ptr) {
    cb_func = ptr;
}

void test::call_cb_func() {
    (this->*cb_func)();
}

int main() {
    test t1;
    t1.set_cb_ptr(&test::get_pc);
    t1.call_cb_func();
}

【讨论】:

  • 无效测试::call_cb_func() { (this->*cb_func)();永远不想通过对象内部的指针调用函数。因此,示例中的“this”是一个完全无用的解释。鉴于 C++ 可能是除了 hex 之外最不人道的语法,我们不能简单地猜测如何从 ANOTHER 对象调用函数。
【解决方案2】:

除了 Snps 的答案,您还可以使用 C++11 中的 function wrapper 来存储 lambda 函数:

#include <iostream>
#include <functional>

class test
{
  public:
   std::function<void ()> Func;
   void get_pc();
   void call_cb_func();
   void set_func(std::function<void ()> func);
};

void test::get_pc()
{
  std::cout << "PC" << std::endl;
}

void test::call_cb_func()
{
  Func();
}

void test::set_func(std::function<void ()> func)
{
  Func = func;
}

int main() {
  test t1;
  t1.set_func([&](){ t1.get_pc(); });
  t1.call_cb_func();
}

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2013-06-29
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多