#include<iostream>
using namespace std;
enum Leve{Freshman,Sophomore,Junior,Senior};
enum Grade{A,B,C,D};
class student {
public:
student(unsigned number, Leve leve, Grade grade):number(number),leve(leve),grade(grade){};
void show();
private:
unsigned number : 27;
Leve leve:2;
Grade grade:2;
};
void student::show() {
cout << "number:" << number <<"\tLeve:";
switch (leve) {
case Freshman:cout << "Freshman";
break;
case Sophomore:cout << "Sophomore";
break;
case 2:cout << "Junior" ;
break;
case 3:cout << "Senior";
}
cout << "\tGrade:";
switch (grade) {
case 0:cout << "A";
break;
case 1:cout << "B";
break;
case 2:cout << "C";
break;
case 3:cout << "D";
}
cout << endl;
}
int main() {
student a(4536978, Sophomore, A);
student b(54324783, Freshman, C);
student c(58953611, Junior, D);
cout << "The size of student is " << sizeof(a)<<endl;
a.show();
b.show();
c.show();
return 0;
}
为什么我的代码在 VS Code 环境下无法正确输出 'C' 信息,但在 GCC 下却可以正常输出?这可能是由于与位字段相关的问题。 做了一些研究,这可能与位域填充机制有关,但我不明白为什么。
MSVC 似乎无法正确处理单个位字段中的混合有符号和无符号类型。将枚举的基础类型更改为无符号类型(大小似乎并不重要)可以解决问题:
enum Leve:uint8_t { Freshman, Sophomore, Junior, Senior };
enum Grade:uint8_t { A, B, C, D };