c++ - 函数指针寻址具有多个参数的函数

标签 c++ c pointers function-pointers

<分区>

函数指针是否有可能使用相同返回类型的不同参数来寻址函数,如果没有,任何替代方法都会有帮助..提前致谢

例子:

struct method
{
    char *name;
    void (*ptr)(?);  //? : what to define as arguments for this
};

void fun1(char *name)
{
    printf("name %s\n\r",name);
}
void fun2(char *name, int a)
{
    printf("name %s %d\n\r",name,a);
}

//defined before main()
method def[]=
{
    {"fun1",fun1},
    {"fun2",fun2}
}
//some where in main()
//call for function pointer
def[1].ptr("try", 2);

最佳答案

typedef void (*myfunc)(char *,int);

struct method
{
    char *name;
    myfunc ptr;  
};

method def[]=
{
     //we store fun1 as myfun 
     //type void(char*,int) and use it this way
    {"fun1",(myfunc)fun1},
    {"fun2",fun2}
};

这在理论上是未定义的行为,但实际上它应该适用于大多数平台
* 编辑 -> 这适用于所有平台,就像 printf(const char*,...) 一样。

关于c++ - 函数指针寻址具有多个参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21162149/

相关文章:

c++ - 为什么这不能在我的学校 unix 系统上编译?

C圆形阵列

c - typedef 在 C 中存储指针

c++ - 通过观察者将信号映射到插槽以获得可变数量的参数

c++ - 是否可以保护内存区域免受 WinAPI 的影响?

c++ - 信号 11 可以在从一个寄存器到另一个寄存器的 mov 指令中产生吗?

c++ - Vulkan 层可以在运行时更改吗?

c - 如何在 C 中写入和读取包含另一个结构的结构?

c++ - std::vector 类型引用的无效初始化

C 列表的实现