假设我在C中使用不透明指针进行封装:
myStruct.h
typedef struct myStruct* handle;
handle create(int number);
void increment(const handle aStruct);
myStruct.c
#include "myStruct.h"
struct myStruct
{
int number;
}
handle create(int number)
{
handle newStruct = malloc(sizeof(struct myStruct));
newStruct->number = number;
}
void increment(const handle aStruct)
{
(aStruct->number)++; //Works when typedef'ed despite the const, doesn't work if I use struct myStruct*
}
为什么编译并且数字增加尽管const?更奇怪的是,如果我删除了typedef并使用struct myStruct *,现在const工作并且递增会导致修改只读错误。
sonebody可以解释为什么typedef会改变const行为吗?