C++;:在另一个结构中定义一个结构? 所以我一直在玩C++。我试图弄清楚是否有可能在另一个结构的定义中定义一个结构。这是我的密码 #include <iostream> using namespace std; int main(){ struct structure1{ int integer1; struct structure2{ int integer2; }struct2; }struct1; structure1 *s1 = &struct1; s1->integer1 = 50; cout<<"STRUCTURE ONE'S INTEGER: "<<s1->integer1<<endl; cout<<"STRUCTURE ONE'S STRUCTURE2.integer2: "<<s1->struct2.integer2; }

C++;:在另一个结构中定义一个结构? 所以我一直在玩C++。我试图弄清楚是否有可能在另一个结构的定义中定义一个结构。这是我的密码 #include <iostream> using namespace std; int main(){ struct structure1{ int integer1; struct structure2{ int integer2; }struct2; }struct1; structure1 *s1 = &struct1; s1->integer1 = 50; cout<<"STRUCTURE ONE'S INTEGER: "<<s1->integer1<<endl; cout<<"STRUCTURE ONE'S STRUCTURE2.integer2: "<<s1->struct2.integer2; },c++,struct,C++,Struct,从我在输出中看到的情况来看,它似乎在工作。但我只是不明白它为什么或者是如何工作的。这是个好习惯吗?这有什么应用吗 谢谢 但我只是不明白它为什么或者是如何工作的 为什么它不起作用?这是完全合法的C++。 这是个好习惯吗 取决于它的使用方式 这有什么应用吗 当然。例如,当您只需要structure2内部structure1而不需要其他内容时。最好使其范围尽可能小 更多信息:除了缺少初始化的integer2@E\u net4之外,似乎没有什么问题,但由于某种原因,我键入的内容似乎被切断了,我已将其余内

从我在输出中看到的情况来看,它似乎在工作。但我只是不明白它为什么或者是如何工作的。这是个好习惯吗?这有什么应用吗

谢谢

但我只是不明白它为什么或者是如何工作的

为什么它不起作用?这是完全合法的C++。 这是个好习惯吗

取决于它的使用方式

这有什么应用吗

当然。例如,当您只需要
structure2
内部
structure1
而不需要其他内容时。最好使其范围尽可能小


更多信息:

除了缺少初始化的
integer2
@E\u net4之外,似乎没有什么问题,但由于某种原因,我键入的内容似乎被切断了,我已将其余内容放回。尽管如此,你的问题使你看起来没有阅读C++中的聚合类型和你可以嵌套它们的事实。我不能把它投射出来,但是这是一个很有用的语法,因为它是有效的语法。我以前见过这种用法。通常声明仅由该类或结构在内部使用的枚举或其他结构。
$ ./a.out
STRUCTURE ONE'S INTEGER: 50
STRUCTURE ONE'S STRUCTURE2.integer2: 0