在C语言中是否可以具有函数的结构或并集?

2 c struct function unions

有没有办法(无论是并集,结构还是其他方式)具有一组功能?

typedef struct {
    //ERROR
    int sqr(int i) {
        return i * i;
    }
    //ERROR
    int cube (int i) {
        return i * i * i;
    }
} test;
Run Code Online (Sandbox Code Playgroud)

M O*_*ehm 6

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

struct Interface {
    int (*eval)(int i);
};
Run Code Online (Sandbox Code Playgroud)

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

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 };
Run Code Online (Sandbox Code Playgroud)

然后像正常函数一样调用这些字段:

printf("%d\n", squarer.eval(4));    // "16"
printf("%d\n", cuber.eval(4));      // "64"
Run Code Online (Sandbox Code Playgroud)