C++: unions with methods?

后端 未结 2 766
执念已碎
执念已碎 2020-12-31 00:33

Is there anything wrong with a union having one or more methods? Or anything to watch out for? (I can see constructors/destructors being problematic for schizophrenic reason

2条回答
  •  轮回少年
    2020-12-31 01:16

    From the C++03 & C++0x (Draft N3092) standards:

    9.5 Unions
    A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class.

    Initializing the union using the aggregate initializer syntax (U u = { 42 };) or setting a member afterwards (U u; u.i = 42;) is not "problematic". And neither is initializing it using a constructor (U u( 42 );).
    The only "catch" is that you cannot use the aggregate initializer syntax for a union that has a user defined constructor.

提交回复
热议问题