你們的問題「我猜」是結構確定指標
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]。 –