結構體
結構體是一個由程序員定義的數據類型,可以容納許多不同的數據值
- 結構體中可以有什麼
(1) 各種數據類型、數組、指針(包括this指針)等
(2) 函數 - 結構體聲明
結構體聲明的格式是struct StructName {內容};
struct men {
int age;
int height,weight;
men(int a, int h, int w) {
age = a;
height = h;
weight = w;
}
void fight() {
cout << "Fighting!!!" << endl;
}
void show() {
cout << "my age is " << age << endl;
cout << "my height is " << height << endl;
cout << "my weight is " << weight << endl;
}
};
- C++結構體和類的異同
相同之處
(1) 結構體中可以包含函數,也可以定義public、private、protected數據成員
(2) 結構體中可以繼承和被繼承
struct men {
public:
int age;
int height,weight;
men(int a, int h, int w) {
age = a;
height = h;
weight = w;
}
void fight() {
cout << "Fighting!!!" << endl;
}
void show() {
cout << "my age is " << age << endl;
cout << "my height is " << height << endl;
cout << "my weight is " << weight << endl;
}
};
struct student:men {
int grade;
student(int a,int h,int w,int g):men(a,h,w) {
grade = g;
}
};
- 結構體初始化
(1) 賦值初始化
賦值初始化有兩種情況,第一種是完全賦值,如下所示
struct bird {
int weight;
int type;
int age;
void show() {
cout << "this bird's weight is " << weight << endl;
cout << "this bird's type is " << type << endl;
cout << "this bird's age is " << age << endl;
}
};
int main() {
bird mybird = {1,2,3};
mybird.show();
return 0;
}
第二種是部分賦值,如下所示
struct bird {
int weight;
int type;
int age;
void show() {
cout << "this bird's weight is " << weight << endl;
cout << "this bird's type is " << type << endl;
cout << "this bird's age is " << age << endl;
}
};
int main() {
bird mybird = {1,2};
mybird.show();
return 0;
}
要注意的是部分賦值是按順序賦值的,上面代碼只給weight和age賦值,age沒有被賦值。
(2) 構造函數初始化
可以看到,賦值初始化雖然簡單易操作,但是不太靈活,使用構造函數可以很靈活地來初始化結構體
struct men {
public:
int age;
int height,weight;
men(int a, int h, int w) {
age = a;
height = h;
weight = w;
}
void fight() {
cout << "Fighting!!!" << endl;
}
void show() {
cout << "my age is " << age << endl;
cout << "my height is " << height << endl;
cout << "my weight is " << weight << endl;
}
};
int main() {
men qzq(1,2,3);
return 0;
}
- 結構體使用
如何使用結構體?答案是就那麼使用,看上面的例子就知道了,不多說。
聯合體
利用union可以用相同的存儲空間存儲不同型別的數據類型,從而節省內存空間。用聯合體可以很方便地將4個字節的int類型拆分成四個字節,這在用串口發送數據的時候很方便。
union DataType {
int n;
char s[12];
double d;
};
int main() {
DataType data;
data.n = 10;
printf("%x %x %x %x\n",data.s[0], data.s[1], data.s[2], data.s[3]);
return 0;
}
聯合體中的所有數據的基址都一樣。
枚舉類型
枚舉類型是C++的一種派生數據類型,它是由用戶定義的若干枚舉常量的集合,通過字符的描述來增加程序的可讀性。枚舉的元素本質是int類型。
定義方法enum 類型名{常量列表}
enum food {
meat, rice, fruit
};
其中meat爲0,rice爲1,fruit爲2.可以看出,默認以0開始,常量的值可以相同,比如
enum food {
meat=0, rice=0, fruit=0
};
未指定值的常量,默認從前一個常量的值開始遞增,如下
enum food {
meat=7, rice, fruit
};
其中meat爲7,rice爲8,fruit爲9