C++: unions with methods?

北战南征 提交于 2019-11-29 11:47:25

问题


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 reasons)


回答1:


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.




回答2:


How could you possibly implement such a thing? Here's a pointer to a union, hope you don't mind that you have no idea which variables are safe to use and which aren't.

Unions are a dead language feature really anyway- they've been totally superseded by library-based methods like boost::variant or boost::any. Kind of similar to the void* and functional macros - they're very rarely useful in C++ compared to other options.



来源:https://stackoverflow.com/questions/4056256/c-unions-with-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!