2012-07-21 117 views
0

我有这样的代码定义结构(传入是简单的结构)C++在阵列结构体的成员函数指针表示编译错误

#define FUNCS_ARRAY 3 

    struct func 
    { 
     void (AA::*f) (incoming *); 
     int arg_length; 
    }; 

    func funcs[FUNCS_ARRAY]; 

然后在此类AA体我这样定义指针数组:

funcs[0] = { &AA::func1, 4 }; 
funcs[1] = { &AA::func2, 10 }; 
funcs[2] = { &AA::func2, 4 }; 

当我尝试经由所述阵列即时得到编译错误调用的功能中的一个:
如果我这样称呼它(p是进入):

(*funcs[p->req]->*f)(p); 

即时得到这样的错误:

error: no match for ‘operator*’ in ‘*((AA*)this)->AA::funcs[((int)p->AA::incoming::req)]’ 

当我尝试调用它是这样的:
(funcs中[对 - > REQ] - > * F)(对);
即时得到:

error: ‘f’ was not declared in this scope 

当我试试这个:

(funcs[p->req].f)(p); 

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((AA*)this)->AA::funcs[((int)p->AA::incoming::req)].AA::func::f (...)’, e.g. ‘(... ->* ((AA*)this)->AA::funcs[((int)p->AA::incoming::req)].AA::func::f) (...)’ 

什么是访问函数指针在侧结构的正确方法?

+0

你可以使用['标准:: function'(http://en.cppreference.com/w/cpp/utility/functional/function)或[ 'boost :: function'](http://www.boost.org/libs/function/)来做所有的事情为你包装 – KillianDS 2012-07-21 14:35:31

回答

3

要通过指向成员函数来调用成员函数,您需要该指针和相应类的实例。

在你的情况下,指向成员的指针是funcs[i].f,我假设你有一个AA的实例,名为aa。然后,你可以这样调用该函数:

(aa.*(funcs[p->req].f))(p); 

如果aa是一个指针到AA,那么语法是:

(aa->*(funcs[p->req].f))(p); 

如果你从内主叫(非的AA静态)成员函数,然后尝试:

(this->*(funcs[p->req].f))(p); 
+0

如果AA类中的方法在电话号码的内部,那么电话就是一个...... – user63898 2012-07-21 14:44:12

+0

在这种情况下使用'this'。 – Mat 2012-07-21 14:46:53

+0

我用过这个 - > *,谢谢! – user63898 2012-07-21 14:47:05