zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    B Graph(异或MST)
    G. Xor-MST(边权为俩点值的异或值,求MST)
    H Harmony Pairs(找(大小)和(位数和大小)逆序的点对,数位dp)
    hdu6787(根据喜欢程度分配得最大总价值,最大费用最大流)
    Codeforces Global Round 2
    2019西北工业大学程序设计创新实践基地春季选拔赛(重现赛)
    Java EE学习笔记(九)
    Java EE学习笔记(八)
    Codeforces Round #549 (Div. 2)
    Codeforces Round #550 (Div. 3)
  • 原文地址:https://www.cnblogs.com/invisible/p/2380940.html
Copyright © 2011-2022 走看看