【问题标题】:Constructor and anonymous union with const members带有 const 成员的构造函数和匿名联合
【发布时间】:2011-09-26 09:19:00
【问题描述】:

是否可以与 const 成员建立匿名联合?我有以下内容:

struct Bar {
  union {
    struct { const int x, y; };
    const int xy[2];
  };
  Bar() : x(1), y(2) {}
};

使用 G++ 4.5 我得到错误:

error: uninitialized member ‘Bar::<anonymous union>::xy’ with ‘const’ type ‘const int [2]’

【问题讨论】:

  • struct { const int x, y; }; 不是有效的 C++。你是在问你是否可以用 GCC 做点什么?
  • 为什么无效?是否需要带有初始化列表的构造函数?
  • GCC -pedantic 开关似乎很有用。 “ISO C++ 禁止匿名结构”它说。如果我删除上面的consts,我会收到同样的警告。

标签: c++ constructor constants unions


【解决方案1】:

是的。它是可能的,但是您必须在构造它时对其进行初始化。你不能让它未初始化。但在这种特殊情况下,我认为这是不可能的,因为您无法在初始化列表中初始化数组。

顺便看看这个有趣的话题:

【讨论】:

    【解决方案2】:

    没有。尝试使用 GCC 的 -pedantic 开关:

      warning: ISO C++ prohibits anonymous structs
    

    因此,删除 consts 的示例也是非法的。

    【讨论】:

    • 恐怕这不能回答问题。禁止匿名结构,但禁止匿名联合。
    • @SamHocevar 谢谢!感谢您的贡献,但从技术上讲,答案肯定是否定的:我在寻找合法的 C++。
    • 也许您可以编辑问题,那么?它指出“是否有可能与 const 成员建立匿名联合”,答案似乎是肯定的。您似乎对匿名structs 有不同的问题。
    【解决方案3】:

    这是 GCC 中的一个问题,已在 4.6 版中修复。您的代码现在可以正常工作了。

    它仍然依赖于 GCC 扩展,因为它使用匿名结构,但现在大多数编译器都支持它们。此外,现在可以使用-pedantic 正确构建以下代码:

    struct Bar {
      union {
        const int x;
        const int y;
      };
      Bar() : x(1) {}
    };
    

    Clang 和 Visual Studio 2010 也接受该代码(但在 2008 中失败)。

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 2015-08-10
      • 1970-01-01
      • 2020-11-21
      相关资源
      最近更新 更多