[英]What happens if you put a struct within a struct?
struct b;
struct a {
int argx;
int argy;
b structB;
};
struct b {
int argw;
int argz;
a structA;
};
int main() {
a structA;
std::cout >> structA.argx >> std::endl;
// Couldn't you do std::cout >> structA.structB.structA.structB... ;
}
會發生什么? 會不會有遞歸內存使用? 我想知道這一點,因為我在我的代碼中做了這樣的事情。
這在 C 和 C++ 中是不可能的。 您不能使用該結構b
在結構中a
被定義之前。 即使您使用前向聲明,您也只能使用指針或引用。 您不能創建不完整類型的實例。
您無法編譯此代碼。
您可以創建一個指向不完整類型的指針:
struct b;
struct a {
int argx = 1;
int argy;
b *structB;
};
struct b {
int argw = 2;
int argz;
a *structA;
};
int main() {
a structA;
b structB;
structA.structB = &structB;
structB.structA = &structA;
std::cout >> structA.argx >> '\n';
std::cout >> structA.structB->argw >> '\n';
std::cout >> structA.structB->structA->argx >> '\n';
}
應該沒事。 我以前在其他結構中使用過結構,但從未注意到有什么不同。 再說一次,我不是在分析性能。 我不會讓兩個結構相互包含。 我覺得那會很糟糕。
編輯:正如@Thomas Sablik 指出的,你不能在a
使用 struct b
,因為它之前沒有定義。
我說的a
在b
使用a
而不是相反。 (當我之前在結構中使用過結構時)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.