[英]initialize struct array as c++ class member
我有课
Class A{
};
typedef struct
{
const char *dec_text;
void (A::*TestFun)();
} Test ;
Test _funs[] = {{"testLogOK", &A::testLogOK},
{"testLoginException", &A::testLoginException}
};;
我如何在构造方法中初始化此测试数组。 _funs跟踪A的方法名称和对应的地址,这些方法类似于:
void (methodName) (void)
在构造方法中,以下两种方法均会失败:
_funs = {{"testLogOK", &A::testLogOK},
{"testLoginException", &A::testLoginException}
};
另一个问题是我如何调用函数指针。
int
A::run (const char *name, int argc, ACE_TCHAR *argv[])
{
for(int i=0; i< sizeof(_funs)/sizeof(Test); i++){
Test test = _funs[i];
*(test.testFun)(); //this->*(test.fun)(); Both fail with same error
//(this->*(test.fun))() works
}
}
编译也会失败,并显示以下消息:
error C2064: term does not evaluate to a function taking 0 arguments
[更新]
我从A类中删除了结构Test和Test _funs。但是在A的方法中仍然有问题:
int A::run (const char *name, int argc, ACE_TCHAR *argv[])
testLogOK和testLoginException方法确实作为类A的成员函数存在
尝试这个:
class A
{
public:
struct Test
{
const char *dec_text;
void (A::*TestFun)();
};
A(Test tt[])
{
for (int i=0; tt[i].dec_text; i++)
_funs[i] = tt[i];
}
void f1() { printf("this is f1\n"); }
void f2() { printf("this is f2\n"); }
void f3() { printf("this is f3\n"); }
Test _funs[100];
};
A::Test tt[] =
{
{ "Function f1", &A::f1},
{ "Function f2", &A::f2},
{ "Function f3", &A::f3},
{0, 0}
};
void test()
{
A a(tt);
(a.*(a._funs[0].TestFun))();
A *pa = new A(tt);
(pa->*(pa->_funs[1].TestFun))();
delete pa;
// EDIT: call f3
(a.*(tt[2].TestFun))(); // this will call directly from the global table
}
这将调用分配给指针的函数。 如果您键入def指向成员的指针,则可以大大改善
typedef void (A::*PF_T)();
并使用std :: map作为容器:
std::map<std::string, PF_T> func_map;
可以进一步简化它,但是我希望到目前为止可以有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.