错误:联合中不允许复制赋值运算符

发布于 2024-09-30 02:09:02 字数 322 浏览 0 评论 0原文

当出现以下错误时,我正在编译下面的代码。我无法找到原因。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随风而去 2024-10-07 02:09:02

为了拥有某种类类型 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.

尝蛊 2024-10-07 02:09:02

编译器尝试为 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 the union if not known, so it falls back to a bit-for-bit copy of the object. However, it can't do that either, since struct { const int j; } has a non-trivial assignment operator.

See http://gcc.gnu.org/ml/gcc-help/2008-03/msg00051.html.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文