【问题标题】:C++: defining a struct inside another struct? [duplicate]C++:在另一个结构中定义一个结构? [复制]
【发布时间】: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的骗子
  • 它有效,因为它是有效的语法。我以前见过这个。通常声明一个枚举或另一个结构,它们只会被该类或结构在内部使用。

标签: c++ struct


【解决方案1】:

但我就是不明白为什么或如何工作。

为什么它不起作用?这是完全合法的 C++。

这是好的做法吗?

取决于它的使用方式。

这有什么应用吗?

当然。例如,当您只需要在 structure1 内的 structure2 而其他地方都不需要时。让它的范围尽可能小是好的。

欲了解更多信息:Why would one use nested classes in C++?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2015-06-03
    • 2013-06-23
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多