c++简单的联合体创建和录取分数方式的运用

#include<iostream>
#include<iomanip>
#include<string>

using namespace std;

class ExamInfo {
private:
    string name;
enum { GRADE , PASS, PERCENTAGE} mode; //枚举 计分方式

union { //无名联合体的创建
    char grade;
    bool pass;
    int percentage;
}; 

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 percentage):name(name),mode(PERCENTAGE),percentage(percentage){}
    void show(); 
};
void ExamInfo::show(){ //show 方法的实现
cout<<name<<":";
switch(mode)
 {
    case GRADE:
        cout<<grade; break;
    case PASS:
        cout<<pass;break;
    case PERCENTAGE:
        cout<<percentage;break; 
 }
 cout<< endl;
 }

int main(){
ExamInfo course1("English",'b');
ExamInfo course2("c",true);
ExamInfo course3("c++",85);
course1.show();
course2.show();
course3.show();
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41814721/article/details/82561542
今日推荐