5月8日打卡
例4-8
题目描述:
使用联合体保存成绩信息,并且输出
代码部分:
#include<string> #include<iostream> using namespace std; class ExamInfo { private: string name; enum { GRADE, PASS, PERCENTAGE }mode; union { char grade; bool pass; int percant; }; public: ExamInfo(string name,char grade):name(name),mode(GRADE),grade(grade){} ExamInfo(string name,bool pass):name(name),mode(PASS),pass(pass){} ExamInfo(string name,int percant):name(name),mode(PERCENTAGE),percant(percant){} void show() { cout << name << ":"; switch (mode) { case GRADE:cout << grade; break; case PASS:cout << (pass ? "PASS" : "FALL"); break; case PERCENTAGE:cout << percant; break; } cout << endl; } }; int main() { ExamInfo couse1("English", 'B'); ExamInfo couse2("Calculus", 'true'); ExamInfo couse3("C++Programming", 85); couse1.show(); couse2.show(); couse3.show(); return 0; }
例4-9
题目描述:
设某次体育比赛的结果有四种可能:胜(WIN)、负(LOSE)、平局(TIE)、比赛取消(CANCEL),编写程序输出这四种情况。
分析:1.设计一个枚举类型一次输出四种可能的结果。
代码部分:
#include<iostream> using namespace std; enum GameResult{WIN,LOSE,TIE,CANCEL}; int main() { GameResult result; enum GameResult omit = CANCEL; for (int count = WIN; count <= CANCEL; count++) { result = GameResult(count); if (result = omit) cout << "The game was cancelled" << endl; else { cout << "The game was cancelled" << endl; if (result == WIN) { cout << "and we won!"; } if (result == LOSE) { cout << "and we lost."; } cout << endl; } return 0; } }