【问题标题】:Nested Structure with anonymous type in C++C ++中具有匿名类型的嵌套结构
【发布时间】:2018-02-01 12:56:24
【问题描述】:

我正在尝试将 C 中的嵌套结构代码移植到 C++ 中。我知道在 C++ 中,内部结构类型将是外部结构类型的成员。就我而言,我有一个没有类型的内部结构(标记为*),我不知道如何将 struct2 完全指定给编译器。

typedef struct struct1
{
    struct // *
    {
        struct struct2
        {
            int bla;
            int bla2;
        } *array;

        int bla3;

    } list;

    int bla4;

} struct1_t;


int main()
{
    struct1_t *st = new struct1_t();

    st->bla4 = 10;
    st->list.bla3 = 45;

    // ?
    st->list.array = new struct1_t::struct2();


    return 0;
}

编辑:上面的结构代码是由 ASN1 编译器自动生成的,我无法对其进行任何更改。

【问题讨论】:

  • 如果您打算以 C++ 方式使用 C++,那么请考虑放弃 C typedef 构造。优先使用别名声明而不是 typedef。结构是 C++ 中的类。
  • 和结构在 C++ 中都是类型
  • 它不是“没有类型的结构”,它是匿名结构类型。但目前还不清楚你的问题到底是什么。只需使用与变量声明分开的专有名称编写普通定义。

标签: c++ struct


【解决方案1】:

这在 C++11 中适用于我:

st->list.array = new decltype( struct1_t::list )::struct2;

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2018-01-27
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多