gpt4 book ai didi

c - c结构中的私有(private)成员

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:23 25 4
gpt4 key购买 nike

我读了很多帖子,比如 How to make struct members private? Hiding members in a C struct但我没有帮助我,这样我有一个头文件

#ifndef TEST_H_
#define TEST_H_
typedef struct point point;
#endif /* TEST_H_ */

和c文件

#include "test.h"
struct point
{
void *data;
};

当我尝试在 main.c 中创建一个点结构的实例时

static point objpoint;
main()
{
}

编译器出现这个错误描述资源路径位置类型

237 变量“objpoint”被声明为一个从未完成的类型 main.c

顺便说一句,如果我定义了一个指向结构的指针

static point *ppoint;

编译器不会产生任何错误

此外,还有一个重要的信息,我需要避免对结构对象进行任何动态分配

请指教。

最佳答案

您不能仅使用前向声明创建类型为 struct point 的对象。

您需要添加函数来构造struct point 的实例并操作其数据。在这些函数中,您只处理指针。

在 .h 文件中添加声明:

#ifndef TEST_H_
#define TEST_H_

typedef struct point point;

point* constructPoint();
void setX(point* p, int x);
void setY(point* p, int y);

int getX(point* p);
int getY(point* p);


#endif /* TEST_H_ */

在 .c 文件中定义 struct 和函数:

#include "test.h"
struct point
{
int x;
int y;
};

point* constructPoint()
{
return calloc(1, sizeof(point));
}

void setX(point* p, int x)
{
p->x = x;
}

void setY(point* p, int y)
{
p->y = x;
}

int getX(point* p)
{
return p->x;
}

int getY(point* p)
{
return p->y;
}

使用函数构造和操作main.c中的对象:

#include "test.h"

int main()
{
point* pt_ptr = constructPoint();
setX(pt_ptr, 10);
printf("%d\n", getX(pt_ptr));
}

关于c - c结构中的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37424557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com