Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

c++ - Can I initialize a union in a mem-initializer?

I'm surprised this doesn't work:

union DlDatum
{
   float  mFloat;
   s32    mInteger;
};

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

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;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C++03 and before you are limited to writing a constructor for your union.

In C++11 the uniform initialization extents the syntax of aggregate initialization to constructor initializer lists. This means that the good old aggregate initializer syntax like

DlDatum d = { 3.0 };

which we all know and love from C and which initializes the first member of the union, can now be used in constructor initializer lists as well

union DlDatum
{
   float  mFloat;
   s32    mInteger;
};

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

This feature only allows you to "target" the first non-static member of the union for initialization. If you need something more flexible, then it is back to writing constructors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...