c++ - 将结构数组初始化为 C++ 类成员

标签 c++ arrays struct initialization function-pointers

我有课

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 类中删除了 struct 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
}

这将调用分配给指针的函数。 如果您对指向成员的指针进行类型定义,这可以得到很大的改进

typedef void (A::*PF_T)();

并使用 std::map 作为容器:

std::map<std::string, PF_T> func_map;

它还可以精简很多,但我希望它能帮助到这一点。

关于c++ - 将结构数组初始化为 C++ 类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132054/

相关文章:

C++ gsoap mime/dime 用于 Windows 中的二进制文件

Java数组创建

c - 正确初始化 C 中的递归结构类型

c++ - 如何调试堆损坏错误?

c++ - 为 C++ 设置窗口

arrays - 在Matlab中从元胞数组中删除连续和不连续的列

c++ - 如何从文本文件中读取值和数组

c - 增加新条目的结构名称 - c

c - 为什么一个结构可以包含指向另一个未定义的结构的指针?

c++ - 为什么 C++ 没有 const 构造函数?