构造函数和带有 const 成员的匿名联合
是否可以与 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]’
Is it possible to have an anonymous union with const members? I have the following:
struct Bar {
union {
struct { const int x, y; };
const int xy[2];
};
Bar() : x(1), y(2) {}
};
With G++ 4.5 I get the error:
error: uninitialized member ‘Bar::<anonymous union>::xy’ with ‘const’ type ‘const int [2]’
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是 GCC 中的一个问题,已在 4.6 版本中修复。您的代码现在工作正常。
它仍然依赖于 GCC 扩展,因为它使用匿名结构,但现在大多数编译器都支持它们。此外,以下代码现在可以使用
-pedantic
正确构建:该代码也被 Clang 和 Visual Studio 2010 接受(但在 2008 中失败)。
This was a problem in GCC that was fixed in version 4.6. Your code now works fine.
It still depends on a GCC extension because it uses an anonymous struct, but most compilers support them now. Also, the following code now builds properly with
-pedantic
:That code is also accepted by Clang and Visual Studio 2010 (but fails with 2008).
是的。这是可能的,但您必须在构造时对其进行初始化。您不能将其保留为未初始化状态。但在这种特殊情况下,我认为这是不可能的,因为您无法初始化初始化列表中的数组。
顺便说一下,看看这个有趣的主题:
Yes. Its possible but you've to initialized it when its constructed. You cannot leave it uninitialized. But in this particular case, I don't think its possible, since you cannot initialize an array in the initialization-list.
By the way, have a look at this interesting topic:
不可以。尝试使用 GCC 的 -pedantic 开关:
因此,删除了
const
后,该示例也是非法的。No. Try using GCC's -pedantic switch:
The example is therefore also illegal with the
const
s removed.