你们的问题“我猜”是结构确定指标
typedef struct test {
int a;
};
这不仅仅是一个结构定义,而是一种类型定义,它缺少的类型名称,它可以是固定的这样
typedef struct test {
int a;
} MyTestStruct;
或者干脆删除typedef
,只需使用struct test
声明它的实例。另外,如果你打算访问它的成员,那么你必须在你访问它的成员的同一个编译单元中提供一个定义,在这种情况下,在你调用它的“main”文件中。
如果你想隐藏的成员(使其不透明结构),尝试这样
struct.h
#ifndef __STRUCT_H__
#define __STRUCT_H__
struct test; // Forward declaration
struct test *struct_test_new();
int struct_test_get_a(const struct test *const test);
void struct_test_set_a(struct test *test, int value);
void struct_test_destroy(struct test *test);
#endif /* __STRUCT_H__ */
然后,你将不得不
struct.c
#include "struct.h"
// Define the structure now
struct test {
int a;
};
struct test *
struct_test_new()
{
struct test *test;
test = malloc(sizeof(*test));
if (test == NULL)
return NULL;
test->a = DEFAULT_A_VALUE;
return test;
}
int
struct_test_get_a(const struct test *const test)
{
return test->a;
}
void
struct_test_set_a(struct test *test, int value)
{
test->a = value;
}
void
struct_test_destroy(struct test *test)
{
if (test == NULL)
return;
// Free all freeable members of `test'
free(test);
}
这种技术实际上非常优雅,并且有很多优点,最重要的是您可以确保结构使用正确,因为没有人可以直接设置值,因此没有人可以设置无效/不正确的值。而且,如果某些成员是使用malloc()
动态分配的,则可以确保在用户在指针上调用_destroy()
时释放它们。您可以控制您认为合适的值的范围,并在适用的情况下避免缓冲区溢出。
请更具体地说明您的问题。 – Petr
请先阅读[问]页面。 –
@Petr,没有涉及.cpp文件。看代码,它是[tag:c]。 –