我有一个像这样的结构(我将 C struct
编码为 C++ class
来演示我的想法;但我正在使用 C 工作。 ):
//This is a source file
typedef struct _MyType
{
void test() { printf("works!"); }
}MyType;
但我想这样定义我的结构:(这不起作用)
//This is a header file
typedef struct _MyType
{
void test();
}MyType;
//This is a source file
MyType::test() { printf("works!"); }
我已经尝试了更多的事情,但我不能再这样做了。 (我想使用像类
一样的结构
)
如何在 C 中实现类似 OOP 的分离?
最佳答案
在 C 编程中,您不能在 struct
中定义函数。
但是,您可以在 struct
中包含函数指针
类似这样的:-
typedef struct{
void (*test)();
}MyType;
void test(MyType* self) { printf("works!"); }
int main()
{
MyType *m =malloc(sizeof(MyType));
m->test=test;
m->test(m);
free(m);
}
关于c - 如何在 header 中构造函数,在源代码中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18303645/