在C.与原始OOP想法进行实验初步OOP用C
main.c中:
#include <stdio.h>
#include <stdlib.h>
#include "reptile.h"
int main()
{
const char *name = "Spot";
turtle_t *t = maketurtle(name);
t->hide(t); // <---- "Error: dereferencing pointer to incomplete type"
return 0;
}
reptile.h:
#ifndef REPTILE_H
#define REPTILE_H
typedef struct turtle_t turtle_t;
turtle_t* maketurtle(const char *name);
void hide(turtle_t *self);
#endif // REPTILE_H
reptile.c:
#include <stdio.h>
#include <stdlib.h>
#include "reptile.h"
typedef struct turtle_t
{
int numoflegs;
const char name[25];
void (*hide)(turtle_t *self);
} turtle_t;
turtle_t* maketurtle(const char *name)
{
turtle_t *t = (turtle_t*)malloc(sizeof(turtle_t));
t->name = name;
return t;
}
void hide(turtle_t *self)
{
printf("The turtle %s has withdrawn into his shell!", self->name);
}
有什么我失踪?我在堆栈溢出中看过类似的情况,我的代码至少在结构上看起来相同,所以我有点困惑。提前致谢!
p.s.如果这是一个链接器错误,我该如何让它在IDE中编译而不会引发错误?
注意,请考虑在您的方法名称前加上它们所属的类型以避免潜在的命名冲突。 –
另一方面说明:你应该写一个'name'变量的硬拷贝,不要让指针指向字符串。也就是说,用strcpy替换't-> name = name;'。 – Lundin
第三方说明:考虑让你的函数成为'static'。即使你使用你的结构和指向函数的指针,实际的函数本身仍然可以是“静态”的。这可避免在与可能包含具有相同名称的导出函数的其他文件链接时发生名称冲突。 –