18

クラスのメンバー関数へのポインターを別の関数に渡そうとする小さなプログラムを作成しました。私が間違っているところを教えてください..?

#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
4

2 に答える 2

21

関数ポインターを にキャストすることはできません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();
}
于 2013-08-09T17:21:26.950 に答える
3

Snps の回答に加えて、C++ 11の関数ラッパーを使用してラムダ関数を格納することもできます。

#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();
}
于 2016-11-03T09:14:16.260 に答える