在c++中如何从指针数组调用函数到类方法?



我对c++还是个新手我有这样的代码:

in my class.hpp

class Dummy {
private:
void    f1(void);
void    f2(void);
void    f3(void);
void    f4(void);
public:
void caller(std::string id);
};

in my class.cpp

void Dummy::caller( std::string id ) {
// something something about qualifiers requires Dummy::*f instead of just *f
void    (Dummy::*f[4])() = {&Dummy::f1, &Dummy::f2, &Dummy::f3, &Dummy::f4};
string v[4] = {"f1", "f2", "f3", "f4"};

for (int i = 0; i < 4; i++) {
if (id == v[i]) {
(*f[i])();
break ;
}
}
}

这个(*f[i])()在C代码中是有效的,但由于某种原因在c++中,它向我显示了这个错误,我搜索了,但不幸的是,发现没有什么有用的,除了std::invoke,这是在c++ 17(?),我绑定到c++ 98错误:

Class.cpp:41:5: error: indirection requires pointer operand ('void (Dummy::*)()' invalid)
(*f[i])();
^~~~~

好吧,这不是c++的工作方式…仅仅因为你定义了像

这样的函数
void    f1(void);
void    f2(void);
void    f3(void);
void    f4(void);

并不意味着你可以像处理数组

那样访问或处理它们。但这是解决问题的关键,您可以创建一个函数数组,并通过索引

调用它。

这里有一个简短的例子来说明如何做到这一点:

#include <iostream>
void f1(void)
{
std::cout << "you are in f1" << std::endl;
}
void f2(void)
{
std::cout << "you are in f2" << std::endl;
}
void f3(void)
{
std::cout << "you are in f3" << std::endl;
}
void f4(void)
{
std::cout << "you are in f4" << std::endl;
}

void (*p[4]) (void);
int main(void)
{
int result;
int i, j, op;
p[0] = f1;
p[1] = f2;
p[2] = f3;
p[3] = f4;
for(auto i= 0; i<4; ++i)    
{
(*p[i])();
}

return 0;
}

最新更新