c - 在 C 中是否可能有一个结构或函数 union ?

标签 c function struct unions

有没有什么办法,无论是 union、struct 还是其他东西,都有一组函数?

typedef struct {
    //ERROR
    int sqr(int i) {
        return i * i;
    }
    //ERROR
    int cube (int i) {
        return i * i * i;
    }
} test;

最佳答案

结构中的字段可以是函数指针:

struct Interface {
    int (*eval)(int i);
};

您不能在结构体中定义函数,但可以将具有相同签名的函数分配给结构字段:

int my_sqr(int i) {
    return i * i;
}

int my_cube(int i) {
    return i * i * i;
}

struct Interface squarer = { my_sqr };
struct Interface cuber = { my_cube };

然后像普通函数一样调用字段:

printf("%d\n", squarer.eval(4));    // "16"
printf("%d\n", cuber.eval(4));      // "64"

关于c - 在 C 中是否可能有一个结构或函数 union ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58139278/

相关文章:

c - strcpy 使程序崩溃

c - 为什么我不能检索我的灵活数组成员大小?

c - 多次运行函数时的不同结果 - C

arrays - Swift - 混洗过滤后的结构数组不会改变原始数组

关于静态变量优化的 C 分支

vb.net - 具有多个输出的 VB 函数 - 结果分配

objective-c - 无法访问 C 函数体中的 Objective-C 类实例变量

c - 结构和 union 之间的区别

go - 如何使用反射来设置嵌套的结构域值