【发布时间】:2015-05-24 05:46:47
【问题描述】:
所以我一直在玩 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;
}
输出:
$ ./a.out
STRUCTURE ONE'S INTEGER: 50
STRUCTURE ONE'S STRUCTURE2.integer2: 0
从我在输出中看到的,它似乎正在工作。但我只是不明白它为什么或如何工作。这是好习惯吗?这有什么应用吗?
谢谢!
【问题讨论】:
-
除了缺少
integer2的初始化之外,似乎没有什么问题。 -
@E_net4 我做了,但是我输入的内容似乎由于某种原因被截断了,我已经把剩下的放回去了。
-
尽管如此,您的问题使您看起来好像还没有阅读过 C++ 中的聚合类型以及可以嵌套它们的事实。
-
我不能投,但这是stackoverflow.com/q/4571355/560648的骗子
-
它有效,因为它是有效的语法。我以前见过这个。通常声明一个枚举或另一个结构,它们只会被该类或结构在内部使用。