C++复合类型
1.概要:
2.结构体
a.定义结构型的变量时,可以省略 struct 关键字
b.可以定义成员函数,在结构体中的成员函数内部可以直接访问本结构体的成员,无需通过 “.” 或 “->”
代码示例:
//C++的复合类型
#include <iostream>
#include <cstring>
using namespace std;
void testStruct(){
struct Student{
int age;//成员变量
char name[256];//成员变量
void getinfo(){//成员函数,c++结构体中允许出现成员函数
//c的结构体当中不允许有函数
cout << name << ":" << age << endl;//成员函数当中直接访问,不需要./->
}
};
/*struct*/ Student s;
s.age = 22;
strcpy(s.name,"张三");
cout << s.name << ":" << s.age << endl;
s.getinfo();
}
int main(void){
testStruct();
return 0;
}
day01$./07_type
张三:22
张三:22
注意:在给一个
char
型数组赋值的时候不能用=
;数组名是不让改的,应该使用标准C库的函数:strcpy
。
3.联合体
a.定义联合型的变量时,可以省略union
关键字
代码示例:
//联合体
#include <iostream>
using namespace std;
void testUnion(){
union A {
int i;
char c[4];
};
/*union*/ A a;// 可以省略union关键字
}
b.支持匿名联合体
代码示例:
//联合体
#include <iostream>
using namespace std;
void testUnion(){
union /*A*/{//匿名联合体
int i;
char c[4];
};
// 无需变量名,直接访问成员
// 匿名联合体不是希望定义变量,它的主要目的:想体现成员内存的排布方式(共用同一块内存空间)
i = 0x12345678;//小低低 - 小端字节序 低数位 占 低地址
cout << hex << (int)c[0] << ' ' << (int)c[1] << ' ' << (int)c[2] <<' ' << (int)c[3] << endl;
}
int main(void){
testUnion();
return 0;
}
day01$./07_type
78 56 34 12
- 匿名联合体不是希望定义变量,它的主要目的:想体现成员内存的排布方式(共用同一内存空间)
把
union {};
去掉,i
和c
就不会共用一块内存空间了,它两就变成函数testUnion
内部的两个不同的局部变量了,占用的一定是不同的内存空间。
- “聪明的”
cout
当
cout
发现你给它的数据是char
类型的数据,它不会把数据本身打出来,而是把数据对应的字符打出来,但是现在我不想按字符打,就把数据打出来;解决办法是把给cout
的数据类型改一改,做个类型转换,eg :(int)c[0]……
但仍然有个问题,强转成
int
以后确实会把数据打出来,但是默认按十进制打印,但我们给的是十六进制,我们想直接让它按十六进制打出来,在前面加上hex
即可。
4.枚举
a.定义枚举型的变量时,可以省略 enum 关键字
代码示例:
//枚举
#include <iostream>
using namespace std;
void testEnum(){
enum Color {
red,green,blue
};
/*enum*/ Color c;
}
b.独立的类型,和整型之间不能隐式转换.
eg : Color c = 0;
// 在C语言中可以,但是在C++当中不行(c++对类型检查更严格)
要注意的是:只要
=
两边的类型不一致,编译器要做的第一件事情就是类型转换。
代码示例:
//枚举
#include <iostream>
using namespace std;
void testEnum(){
enum Color {
red,green,blue
};
/*enum*/ Color c = red;
cout << "c = " << c << endl;
}
int main(void){
testEnum();
return 0;
}
day01$./07_type
c = 0
结果虽然是
0
,但我们不能给c
直接赋值为0
,直接把0
丢给它,编译器会认为它是int
类型,而把red
赋值给它,编译器会把c
当作是Color
类型,从而不会报错。
5.布尔类型(补充)—C99标准
- 表示布尔量的数据类型 type.cpp
- bool
- 布尔类型的字面值常量
- true 表示真
- false 表示假
- 布尔类型的本质
- 单字节整数,用 1 和 0 表示真和假
- 任何基本类型都可以被隐式转换为布尔类型
- 非 0 即真,0 即假
代码示例(type.cpp
):
#include <iostream>
using namespace std;
void testBool(){
//bool a = true;
//bool b = false;
//bool a = 123;//true
//bool b = 0;//false
//bool a = 0.0000001;//true
//bool b = 0.0000000;//false
//bool a = "adsjfsb";//true 字符串字面值 把地址转成bool
//bool b = "";//true(存的是`\0`)
bool a = "adsjfsb";//true 字符串字面值 把地址转成bool
bool b = NULL;//false
cout << boolalpha << "a = " << a << ",b = " << b << endl;
}
int main(void){
testBool();
return 0;
}