错误:联合中不允许复制赋值运算符
当出现以下错误时,我正在编译下面的代码。我无法找到原因。
typedef union {
struct {
const int j;
} tag;
} X;
int main(){
return 0;
}
错误:成员`<`匿名联合>::`<`匿名结构> `<`匿名联合>::联合中不允许带有复制赋值运算符的标记
不过,此代码使用 gcc 编译会产生罚款。仅使用 g++ 时出现错误。
I am compiling the code below when the following erro comes up. I am unable to find the reason.
typedef union {
struct {
const int j;
} tag;
} X;
int main(){
return 0;
}
error: member `<`anonymous union>::`<`anonymous struct> `<`anonymous union>::tag with copy assignment operator not allowed in union
This code compiles fines with gcc though. Gives error only with g++.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了拥有某种类类型
T
的联合体的成员,T
的特殊成员函数(默认构造函数、复制构造函数、复制赋值运算符和析构函数)一定是微不足道的。也就是说,它们必须是编译器隐式声明和定义的。您的未命名结构没有一个简单的复制赋值运算符(事实上,它根本没有),因为它有一个 const 限定的成员变量,这会抑制隐式声明的生成复制赋值运算符。
In order to have a member of a union of some class type
T
,T
's special member functions (the default constructor, copy constructor, copy assignment operator, and destructor) must be trivial. That is, they must be the ones implicitly declared and defined by the compiler.Your unnamed struct does not have a trivial copy assignment operator (in fact, it doesn't have one at all) because it has a member variable that is
const
-qualified, which suppresses generation of the implicitly declared copy assignment operator.编译器尝试为
union
本身生成赋值运算符,但会失败,因为union
的活动字段未知,因此它会回退到位换 -对象的位副本。但是,它也不能这样做,因为struct { const int j; }
有一个不平凡的赋值运算符。请参阅http://gcc.gnu.org/ml/gcc-帮助/2008-03/msg00051.html。
The compiler tries to generate an assignment operator for the
union
itself, and fails because the active field of theunion
if not known, so it falls back to a bit-for-bit copy of the object. However, it can't do that either, sincestruct { const int j; }
has a non-trivial assignment operator.See http://gcc.gnu.org/ml/gcc-help/2008-03/msg00051.html.