[英]cannot declare struct member within a structure in c
我想在頭文件中的不同結構定義中聲明一個結構值。 所以我在頭文件中完成了以下操作。 但編譯器給我錯誤消息field myStructMember has incomplete type
在Ah頭文件中:
struct My_A{
int value;
};
在Bh頭文件中:
struct My_A; // forward declaration
struct My_B
{
struct My_A myStructMember; // error is here!
int differentValue;
};
是否可以在結構聲明中聲明結構成員?
編輯: My_A和My_B在不同的頭文件中聲明。
編輯2:當我在Bh中添加“Ah”時,它就可以了。 它有什么問題嗎? 在Bh頭文件中:
include "A.h" // added this line insead of forward declaration
struct My_B
{
struct My_A myStructMember; // not any error anymore
int differentValue;
};
錯誤就是它所說的 - 在你擁有完整類型之前你不能使用struct。 你根本就不知道它的大小。 前方聲明在這里沒有幫助。
或者,您可以使用指向struct的指針。 指針大小是已知的。
不是沒有#,包括在Bh
Ah
(或者在Bh
之前每次引用它時 - 當編譯器解析My_B
否則它缺少確定My_A
大小所需的信息。您可以使用指針代替,但這會獲得處理的所有開銷他們。
如果您只是想實現抽象/細節隱藏,那么您可以更改My_A
的前向聲明,以便它現在是正確大小的結構(例如,使用char數組)。 然后你必須確保沒有包括Ah
和 Bh
因為這將導致編譯器錯誤。 哦, 真的確保你的尺寸正確或者奇怪的東西會發生。 有一些方法可以使用宏斷言確保這是正確的。
比如做Bh
struct My_A{
char hidden_data[4];
};
struct My_B
{
struct My_A myStructMember;
int differentValue;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.