联合可以包含数据成员以及可以对其进行操作的函数吗? [英] Can a union contain data members as well as functions that can operate upon them?
本文介绍了联合可以包含数据成员以及可以对其进行操作的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Can a union contain data members as well as functions that can operate upon them?
我的尝试:
我没有尝试任何实际的东西,但只想清除这个概念。
What I have tried:
I havent tried anything practically but just want to clear the concept.
推荐答案
是:联盟声明 - cppreference.com [ ^ ]
工会 [ ^ ]。但是,正如微软所说,有比Unions更好的方法。
Unions[^]. However, as Microsoft note, there are better ways than Unions.
是(详见文档)。例如:
Yes (see the documentation for details). Try for instance:
#include <iostream>
using namespace std;
union U
{
double d;
int i;
void incInt(){ ++i;}
void showInt(){ cout << "int value is " << i << "\n";}
void showDouble() { cout << "double value is " << d << "\n";}
};
int main()
{
U u;
u.i = 10;
u.showInt();
u.showDouble();
u.incInt();
u.showInt();
u.showDouble();
}
请现代 C ++
介绍 std :: variant
替代 union
。
这篇关于联合可以包含数据成员以及可以对其进行操作的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文