1.结构体
①结构体的定义:
struct fruit
{
char name[20];
char color[20];
float price;
};
②结构体创建变量:
struct fruit
{
char name[20];
char color[20];
float price;
}apple, balana;
或者
struct fruit
{
char name[20];
char color[20];
float price;
};
fruit apple;
③结构体的初始化:
struct fruit
{
char name[20];
char color[20];
float price;
};
fruit apple =
{
"apple",
"red",
19.99
};
或者
struct fruit
{
char name[20];
char color[20];
float price;
} apple =
{
"apple",
"red",
19.99
};
或者
struct fruit
{
char name[20];
char color[20];
float price;
} apple =
{
"apple",
"red",
19.99
};
fruit apple_new = apple;
④结构体程序实例:
#include <iostream>
using namespace std;
struct fruit
{
char name[20];
char color[20];
float price;
};
int main()
{
fruit apple =
{
"apple",
"red",
19.99
};
fruit pear =
{
"pear",
"yellow",
20.99
};
cout << "the name of the first fruit is " << apple.name << endl;
cout << "the total price of the two fruit is " << apple.price + pear.price << endl;
return 0;
}
2.联合体跟结构体使用情况类似,唯一不同的是联合体所有的属性占用同一块内存空 间,所以联合体所占用的内存 的大小是所有属性中的占用最大的那个。