问题描述
在C ++ 11中,我声明以下联合:
In C++11 I declare the following union:
union U4 {
char c;
int i;
static int si;
};
当我使用-std = c ++ 11 -pedantic-errors在g ++ 4.7.0中编译此代码时,出现以下错误(仅进行了少量编辑):
When I compile this code with g++ 4.7.0 using -std=c++11 -pedantic-errors, I get the following errors (with minor editing):
据我所知,FDIS(N3242)并未明确 allow 命名联合的静态数据成员.但是我也看不到FDIS在哪里不允许 命名联合的静态数据成员.FDIS重复提到了非静态数据成员"可以完成的工作[第9.5节第1节].相比之下,这表明该标准允许联合的静态数据成员.
The FDIS (N3242) does not explicitly allow static data members of named unions, as far as I can see. But I also don't see where the FDIS disallows static data members of named unions either The FDIS does repeatedly refer to what can be done with "non-static data members" [section 9.5 paragraph 1]. By contrast, that suggests the standard permits static data members of unions.
对于联合的静态数据成员,我没有任何用处.如果需要,我可以使用包含匿名联合的类获得足够接近的效果.我只是想了解标准的意图.
I don't have any use in mind for a static data member of a union. If I needed it I could probably get a close enough effect with a class containing an anonymous union. I'm just trying to understand the intent of the standard.
感谢您的帮助.
推荐答案
是的,这是允许的.该标准的第9节在类,结构和联合中使用 class
一词,除非另有明确说明.对静态工会成员的唯一限制是本地工会(9.4.2/5)和匿名工会(9.5/5).
Yes this is allowed. Section 9 of the Standard uses the word class
for classes, structs and unions, unless it explicitly mentions so otherwise. The only restrictions on static union members are for local unions (9.4.2/5) and for anonymous unions (9.5/5).
#include <iostream>
union Test
{
static int s;
};
int Test::s;
int main()
{
Test::s = 1;
std::cout << Test::s;
}
LiveWorkSpace 上的输出.请注意,它可以在Clang 3.2上编译,但不能在gcc 4.8.0或Intel 13.0.1上编译.看来这是gcc/Intel错误.
Output on LiveWorkSpace. Note that it compiles on Clang 3.2 but not on gcc 4.8.0 or Intel 13.0.1. It appears this is a gcc/Intel bug.
这篇关于C ++ 11是否允许非匿名联合包含静态数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!