错误:联合中不允许复制赋值运算符 [英] Error: copy assignment operator not allowed in union

查看:53
本文介绍了错误:联合中不允许复制赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

typedef union {结构{const int j;} 标签;} X;int main(){返回0;}

<块引用>

error: member `<`anonymous union>::`<`anonymous struct>`<`匿名联合>::在联合中不允许使用复制赋值运算符的标签

尽管此代码使用 gcc 编译罚款.仅使用 g++ 出错.

解决方案

为了拥有某个类类型T的联合的成员,T的特殊成员函数(默认构造函数、复制构造函数、复制赋值运算符和析构函数)必须是平凡的.也就是说,它们必须是编译器隐式声明和定义的那些.

您的未命名结构没有简单的复制赋值运算符(实际上,它根本没有),因为它有一个具有 const 限定的成员变量,它抑制了隐式声明的复制赋值运算符.

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++.

解决方案

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.

这篇关于错误:联合中不允许复制赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆