c - 如何在 header 中构造函数,在源代码中定义

标签 c oop struct header-files

我有一个像这样的结构(我将 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/

相关文章:

c - 多维数组分配

c - 了解结构中字符串的动态内存分配

c - 使用返回指针的函数声明为指针是否会导致两个指针链?

c# - 只运行一次的类是否应该包含静态构造函数?

oop - 戈兰 : Is there any way to access the "child" struct in the "parent" struct's methods in Go's composition model?

java - Java 中不同类型的引用对象有什么不同吗?

c++ - 从 std::vector 中删除时出现段错误

C: printf 不打印用户输入的答案

c++ - 如何在C/C++中生成0到用户定义整数之间的随机数?

C中字符串格式的十六进制数转换为0xFFFF格式的wchar_t类型