You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何正确将void(*)(...)类型函数指针声明为结构体成员

问题原因

函数指针完全可以作为结构体成员使用,你的代码编译失败纯粹是函数指针成员的声明语法写错了。
C/C++中普通函数指针的标准声明格式为:

返回值类型 (*指针变量名)(参数类型列表)

你之前写的void(*)(int,int) f把变量名f放到了指针声明括号的外侧,不符合语法规则,编译器无法识别。

修正写法

把变量名放到*后的括号内即可,正确的结构体定义如下:

struct void_func_st{
    void(*f)(int, int); // 变量名f必须放在*后面的括号中
    int a;
};

结合你最开始写的Student静态函数场景,完整可运行的示例代码:

#include <cstdio>
#include <vector>
using namespace std;

struct Student
{
    static void print(int a,int b){
        printf("age is %d, id is %d\n", a, b);
    }
};

struct void_func_st{
    void(*f)(int,int);
    int a;
};

int main(){
    void_func_st test_st;
    test_st.f = &Student::print;
    test_st.a = 1;
    // 调用结构体里的函数指针
    test_st.f(18, 2024001);

    // 该结构体也可以正常放入容器使用
    vector<void_func_st> st_list;
    st_list.push_back(test_st);
    st_list[0].f(17, 2024002);

    return 0;
}
简化写法建议

如果需要多次使用同类型的函数指针,建议提前给类型起别名,避免重复写复杂的指针声明格式:

  • C/C++通用typedef写法
// 定义VoidFunc为对应函数指针类型的别名
typedef void(*VoidFunc)(int, int);

struct void_func_st{
    VoidFunc f; // 直接用别名声明成员即可
    int a;
};
  • C++11及以上版本支持的using写法,可读性更好
using VoidFunc = void(*)(int, int);

struct void_func_st{
    VoidFunc f;
    int a;
};

注意:上述写法只适用于普通全局函数、类静态成员函数的指针存储。如果要存储类的非静态成员函数,函数指针格式需要写成返回值类型 (类名::*指针名)(参数列表),调用时也必须绑定对应类的实例,和静态函数的用法有区别。

内容的提问来源于stack exchange,提问作者mxw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 12:42:17