C++:与方法的联合?
联合体拥有一种或多种方法有什么问题吗?或者有什么需要注意的吗? (我可以看到构造函数/析构函数因精神分裂症的原因而出现问题)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 C++03 & C++0x(草案 N3092)标准:
使用聚合初始值设定项语法 (
U u = { 42 };
) 初始化联合或随后设置成员 (U u; ui = 42;
) 不是“问题” 。并且也没有使用构造函数对其进行初始化 (U u( 42 );
)。唯一的“问题”是您不能对具有用户定义构造函数的联合使用聚合初始值设定项语法。
From the C++03 & C++0x (Draft N3092) standards:
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.
你怎么可能实现这样的事情?这是一个指向联合的指针,希望您不介意您不知道哪些变量可以安全使用,哪些不可以。
无论如何,联合确实是一种已死的语言功能——它们已经完全被基于库的方法(如 boost::variant 或 boost::any)所取代。有点类似于 void* 和函数宏 - 与其他选项相比,它们在 C++ 中很少有用。
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.