在C中尝试原始的OOP思想。
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中编译而不会抛出错误?
答案 0 :(得分:4)
你需要移动你的
typedef struct turtle_t
{
int numoflegs;
const char name[25];
void (*hide)(turtle_t *self);
} turtle_t;
从.c文件到.h文件。不完整类型意味着类型在编译类型中是未知的(只有链接时才会知道它,如果它包含在不同的转换单元中)。这意味着你的main.c turtle_t
只是前向声明的,结构本身是未知的 - 将它移动到.h文件就可以了。
答案 1 :(得分:4)
当编译器在main.c
文件上工作时,它知道有一个名为turtle_t
的结构但它对它一无所知,它没有完全定义。
您需要制作结构&#34; public&#34;,或至少应该公开的部分。这可以通过使用两个结构轻松完成,一个用于公共&#34;方法&#34;和成员变量,以及另一个包含私有数据的嵌套。像
这样的东西typedef struct turtle_private_t turtle_private_t;
typedef struct turtle_t turtle_t;
struct turtle_t
{
turtle_private_t *private; // For private data
void (*hide)(turtle_t *self);
};
作为一种替代方案,一种常见的方法是,您不要在结构中放置公共函数,而是使用普通函数,并在其名称前加上一个特殊的前缀来表示类。像
这样的东西turtle_t *turtle_create(void); // Creates the turtle
void turtle_hide(turtle_t *); // Hides the turtle