C++结构、联合与枚举
8.1 结构:是任意类型元素的集合。
8.1.1 结构布局
结构类型的对象可以被赋值,作为实参传入函数,或者作为函数返回。
struct Readout
{
char hour;
int value;
char seq;
}
布局方式:1 (4);4; 1(4);sizeof(Readout)=12;短长短的风格,剩余空间未使用;
struct Readout
{
int value;
char hour;
char seq;
}
布局方式:4;2(4);sizeof(Readout)=8;第二行剩余2个空间未使用;
struct的名字:
C++中允许在同一个作用域中分别声明一个struct和一个非struct的类型。
例如:struct stat {};
int stat (char *name,struct stat *but);
结构和类:
struct是一种类,它的成员函数默认为public,struct可以包含成员函数,尤其是构造函数。
对于两个struct来说,即使它们成员相同,它们本身仍是不同的类型。
struct S1 {int x};
struct S2 {int y};
S1和S2是两种完全不同的类型,struct本身的类型与其成员的类型也不一样。
S1 x; int i=x;错误。
8.2 联合
union Value{
char *s;
int i;
}
struct Entry {
char *name;
Type t;
Value v;
}
void f (Entry*p)
{
if (p->t==str)
cout<<p->v.s;
}
8.3 枚举
枚举类型用于存放用户指定的一组整数数值,枚举类型的每种取值各自对应一个名字。
枚举类型:
enum class,它的枚举值位于enum的局部作用域,枚举值不会隐式的转换为其他类型。
“普通的enum”,它的枚举值名字与枚举类型本身位于同一个作用域中,枚举值隐式转化为整数值。
8.3.1 enum class
enum class Traffic_light {red,yellow,green};
enum class Warning {green,yellow,orange,red};
Warning a1=7; //错误,不存在int向Warning转化;
int a2= green; //错误,green不位于作用域中;
int a3= Warning::green; //错误,不存在Warning向int转化;
Warning a4=Warning::green;
void f(Traffic_light x)
{
if (x= =9){ } //错误
if (x= =red) { } //错误,当前作用域无red;
if (x= =Warning::red) { } //错误
if (x= =Traffic_light::red) { }
}
enum class Warning:int {green,yellow,orange,red}; //sizeof(Warning= =sizeof(int))
enum class Warning:char {green,yellow,orange,red}; //sizeof(Warning==1)
enum class Flag:char {x=1,y=2,z=4,e=8};
int i =static_cast<int>(Flag::y); //2
char c =static_cast<char>(Flag::e); //8
8.3.2 普通的 enum
enum Traffic_light {red,yellow,green};
enum Warning {green,yellow,orange,red};
Warning a1=7; //错误,不存在int向Warning转化;
int a2= green; /正确,green位于作用域中,转化为int;
int a3= Warning::green; //正确,不存在Warning向int转化;
Warning a4=Warning::green;
void f(Traffic_light x)
{
if (x= =9){ } //ok,但是无这个值
if (x= =red) { } //错误,当前作用域无red;
if (x= =Warning::red) { } //ok
if (x= =Traffic_light::red) { }
}
避免在同一作用域的两个普通枚举中都定义red,易发生二义性。
普通enum enum
enum {arrow_up=1,arrow_down,arrow_sideways};

浙公网安备 33010602011771号