union in cplusplus

C++语言: Codee#25730
01 #include <>iostream>
02 using namespace std;
03
04 union U
05 {
06 private :
07     int i;
08     float f;
09 public :
10     U( int a);
11     U( float b);
12     ~ U();
13     int read_int();
14     float read_float();
15 };
16
17 U :: U( int a)
18 {
19     i = a;
20 }
21
22 U :: U( float b)
23 {
24     f = b;
25 }
26
27 U ::~ U()
28 {
29     cout << "U::~U() \n ";
30 }
31
32 int U :: read_int()
33 {
34     return i;
35 }
36
37 float U :: read_float()
38 {
39     return f;
40 }
41
42 int main()
43 {
44     U x( 12 ), y( 1.9f);
45     cout << x . read_int() << endl;
46     cout << x . read_float() << endl;            // just union in c with member functions
47
48     cout << end << y . read_float() << endl;
49
50     return 0;
51 }

 

C++语言: Codee#25731
01 #include <iostream>
02 using namespace std;
03
04 class SuperVar
05 {
06     enum
07     {
08         character ,
09         integer ,
10         floating_point
11     } vartype;
12     union
13     {
14         char c;
15         int i;
16         float f;
17     };
18 public :
19     SuperVar( char ch);
20     SuperVar( int ii);
21     SuperVar( float ff);
22     void print();
23 };
24
25 SuperVar :: SuperVar( char ch)
26 {
27     vartype = character;
28     c = ch;
29 }
30
31 SuperVar :: SuperVar( int ii)
32 {
33     vartype = integer;
34     i = ii;
35 }
36
37 SuperVar :: SuperVar( float ff)
38 {
39     vartype = floating_point;
40     f = ff;
41 }
42
43 void SuperVar :: print()
44 {
45     switch( vartype)
46     {
47     case character:
48         cout << "character: " << c << endl;
49         break;
50     case integer:
51         cout << "integer: " << i << endl;
52         break;
53     case floating_point:
54         cout << "float: " << f << endl;
55         break;
56     }
57 }
58
59 int main()
60 {
61     SuperVar A( 'c' ), B( 12 ), C( 1.44F);
62     A . print();
63     B . print();
64     C . print();
65
66     return 0;
67 }

转载于:https://www.cnblogs.com/invisible/archive/2012/03/05/2380940.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值