4.24
1 #include <iostream> 2 using namespace std; 3 class DataType 4 { 5 public: 6 DataType(int i) 7 { 8 data.i = i; 9 type = INT; 10 } 11 DataType(char c) 12 { 13 data.c = c; 14 type = CHAR; 15 } 16 DataType(float f) 17 { 18 data.f = f; 19 type = FLOAT; 20 } 21 void Show() 22 { 23 switch (type) 24 { 25 case CHAR: 26 cout << data.c << endl; 27 break; 28 case INT: 29 cout << data.i << endl; 30 break; 31 case FLOAT: 32 cout << data.f << endl; 33 break; 34 default: 35 break; 36 } 37 } 38 private: 39 enum TYPE { INT, CHAR, FLOAT }; 40 union DATA 41 { 42 int i; 43 char c; 44 float f; 45 }; 46 TYPE type; 47 DATA data; 48 }; 49 int main() 50 { 51 DataType a('c'); 52 a.Show(); 53 DataType b(960); 54 b.Show(); 55 DataType c(265.12f); 56 c.Show(); 57 return 0; 58 }
1 #include <iostream> 2 3 using namespace std; 4 5 class Tree { 6 public: 7 Tree(int age = 0) : m_age(age) {} 8 void grow(int years) { 9 m_age += years; 10 } 11 int age() const { 12 return m_age; 13 } 14 private: 15 int m_age; 16 }; 17 18 int main() { 19 Tree t(10); 20 cout << "树龄为:" << t.age() << endl; 21 t.grow(5); 22 cout << "长了5年后树龄为:" << t.age() << endl; 23 return 0; 24 }
1 #include <iostream> 2 using namespace std; 3 4 class CPU { 5 public: 6 CPU(int i, int j, int m, bool n); 7 void show(); 8 private: 9 int m_Hz; 10 int m_zijie; 11 int m_he; 12 bool m_chaopin; 13 }; 14 void CPU::show() 15 { 16 cout << m_Hz << endl << m_zijie << endl << m_he << endl; 17 if (m_chaopin == 1) 18 cout << "true" << endl; 19 else 20 cout << "false" << endl; 21 } 22 CPU::CPU(int i, int j, int m, bool n) 23 { 24 m_Hz = i; 25 m_zijie = j; 26 m_he = m; 27 m_chaopin = n; 28 }