我可以在内存初始化器中初始化联合吗? [英] Can I initialize a union in a mem-initializer?

查看:77
本文介绍了我可以在内存初始化器中初始化联合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶这不起作用:

union DlDatum
{
   float  mFloat;
   s32    mInteger;
};

class DlDbE
{
public:
   DlDbE( float f ) : mData.mFloat( f ) {};
private:
   DlDatum mData;
};

是否可以在c ++构造函数mem-initializer列表中初始化并集?

Is there a way to initialize a union in a c++ constructor mem-initializer list?

更新:答案是为联合创建构造函数。不知道可以做到。这是我所做的:

Update: Answer is to create constructors for union. Didn't know that could be done. Here is what I did:

union DlDatum
{
   float  mFloat;
   s32    mInteger;
   bool   mBoolean;
   u32    mSymbol;
   u32    mObjIdx; 

   DlDatum(         ) : mInteger( 0 ) {}
   DlDatum( float f ) : mFloat( f )   {}
   DlDatum( s32   i ) : mInteger( i ) {}
   DlDatum( bool  b ) : mBoolean( b ) {}
   DlDatum( u32   s ) : mSymbol( s )  {} // this ctor should work for objIdx also
};

class DlDbE
{
public:
   DlDbE() {}
   DlDbE( float f ) : mData( f ) {}
   DlDbE( u32 i   ) : mData( i ) {}
   DlDbE( bool b  ) : mData( b ) {}
   ...etc..
private:
   DlDatum mData;
};


推荐答案

与其他任何成员一样,如果要构建一个工会,您将不得不给工会一个构造函数并调用它。

Like any other member, if you want to construct a union, you will have to give the union a constructor and call that.

这篇关于我可以在内存初始化器中初始化联合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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