有没有什么办法,无论是 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/