【问题标题】:Is it possible in C to have a struct or union of functions?在 C 中是否有可能具有函数的结构或联合?
【发布时间】:2020-01-28 01:25:26
【问题描述】:

有没有什么方法,无论是 union、struct 还是别的什么,都有一组函数?

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

【问题讨论】:

  • 可能,但不是这样。您可以在结构中拥有指向函数的指针。不过,工会没有多大意义。
  • @EugeneSh。例如,可能正在使用 YACC 进行一些解析,并且需要在不同情况下调用或指向不同类型的函数。
  • 为什么要函数集合?
  • @ChristianGibbons 好吧,人们正在收集硬币、邮票和其他奇怪的东西.. 为什么不收集功能呢? :)
  • 这并不像在 C 中尝试那样奇怪 :-)

标签: c function struct unions


【解决方案1】:

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

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"

【讨论】:

    猜你喜欢
    • 2022-12-19
    • 2019-06-13
    • 2023-01-12
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多