gpt4 book ai didi

c - 是否可以在 C 中模拟对象/实例方法?

转载 作者:太空狗 更新时间:2023-10-29 15:20:01 26 4
gpt4 key购买 nike

我知道,因为 C 不是面向对象的,所以我们最接近方法的方法是在结构中使用函数指针。这只是一个思想练习,但是否有可能:

list.add(void* data)

没有将列表本身作为参数传递

我知道:

list.add(list_t* list, void* data)

很容易实现,但是有没有办法,使用 C 的任何部分,以这种方式模拟方法?

我知道答案可能是否定的,但如果可以请向我解释一下!谢谢。

最佳答案

这是我使用可变参数宏 (C99) 得到的最漂亮的语法:

#define call(obj, method, ...) ((obj).method(&(obj), __VA_ARGS__))

usage (click for ideone) :

struct class {
int a;
int (*method)(struct class* this, int b, int c);
};

int code(struct class* this, int b, int c) {
return this->a*b+c;
}

struct class constructor(int a) {
struct class result = {a, code};
return result;
}

#define call(obj, method, ...) ((obj).method(&(obj), __VA_ARGS__))

#include <stdio.h>
int main() {
struct class obj = constructor(10);
int result = call(obj, method, 2, 3);
printf("%d\n", result);
return 0;
}

关于c - 是否可以在 C 中模拟对象/实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17338107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com