2

I've a struct like this (I've coded the C struct like a C++ class to demonstrate what I am thinking; but I am working in C.):

//This is a source file
typedef struct _MyType
{
     void test() { printf("works!"); }
}MyType;

But I want to define my struct like that: (That not works)

//This is a header file
typedef struct _MyType
{
     void test();
}MyType;

//This is a source file
MyType::test() { printf("works!"); }

I've tried some more things but I can't do it again. (I want to use structs like classes)

How can I achieve this OOP-like separation in C?

4

1 回答 1

3

您不能struct在 C 编程中定义函数。

但是你可以在里面有函数指针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);
}
于 2013-08-18T21:32:15.307 回答