c++ primer 学习之路 (15) 4.4 结构简介 结构数组 结构中的位字段

4.4 结构简介

结构是一种比数组更灵活的数据格式,因为同一个结构可以存储多种类型的数据首先,定义结构描述—它描述并标记了能够存储在结构中的各种数据类型。然后按描述创建结构变量(结构数据对象)


关键字struct表明,这些代码定义的是一个结构的布局。标识符inflatable是这种数据格式

的名称,因此新类型的名称为inflatable。这样,便可以像创建char或int类型的变量那样创建inflatable类型的变量了。接下来的大括号中包含的是结构存储的数据类型的列表,其中每个列表项都是一条声明语句。这个例子使用了一个适合用于存储字符串的char数组、一个float和一个double。列表中的每一项都被称为结构成员,因此infatable结构有3个成员

定义结构后,便可以创建这种类型的变量了:

如果您熟悉C语言中的结构,则可能已经注意到了,C++允许在声明结构变量时省略关键字struct:

可以使用成员运算符(.)来访问各个成员。

程序清单说明了有关结构的这些问题,还演示了如何初始化结构。

#include<iostream>
#include<climits>
#include<string>
using namespace std;
struct inflatable
{
 char name[20];
 float volume;
 double price;
};
int main()
{
 inflatable guest =
 {
   "Glorious Gloria",
   1.88,
   29.99
 };
 inflatable pal =
 {
  "auda  asiu",
  3.12,
  32.99
 };
 cout << "Expand your guest list with  " << guest.name;
 cout << "  and   " << pal.name << endl;
 
 cout << "You can have both for $";
 cout << guest.price + pal.price << endl;
 system("pause");
 return 0;
}

始化方式:和数组一样,使用由逗号分隔值列表,并将这些值用花括号括起。

在该程序中,每个值占一行,但也可以将它们全部放在同一行中。只是应用逗号将它们分开:

下面简要地介绍一下结构赋值,程序清单4.12是一个这样的示例。

程序清单4.12 assgn_st.cpp

#include<iostream>
#include<climits>
#include<string>
using namespace std;
struct inflatable
{
 char name[20];
 float volume;
 double price;
};
int main()
{
 inflatable guest =
 {
   "Glorious Gloria",
   1.88,
   29.99
 };
 inflatable choice;
 cout << "guest " << guest.name << " for $ ";
 cout << guest.price << endl;
 choice = guest;
 cout << "choice  " << choice.name << " for $ " << choice.price << endl;
 system("pause");
 return 0;
}

从中可以看出,成员赋值是有效的

可以同时完成定义结构和创建结构变量的工作。为此,只需将变量名放在结束括号的后面即可:

甚至可以初始化以这种方式创建的变量:



4.4.5 结构数组

inflatable结构包含一个数组(name)。也可以创建元素为结构的数组,方法和创建基本类型数组完全相同

inflatable gifts[100];

初始化:

程序清单4.13是一个使用结构数组的简短示例。由于guests是一个inflatable数组,因此guests[0]的类型为inflatable,可以使用它和句点运算符来访问相应inflatable结构的成员。

程序清单4.13 arrstruc.cpp

程序清单4.13是一个使用结构数组的简短示例。由于guests是一个inflatable数组,因此guests[0]的类型为inflatable,可以使用它和句点运算符来访问相应inflatable结构的成员。

程序清单4.13 arrstruc.cpp

#include<iostream>
#include<climits>
#include<string>
using namespace std;
struct inflatable
{
 char name[20];
 float volume;
 double price;
};
int main()
{
 inflatable guests[2] =
 {
  {"Bambi",0.5,21.99},
  {"Godzilla",2000,565.99}
 };
 
 cout << " the guest " << guests[0].name << " and ";
 cout << guests[1].name << endl;
 cout << guests[0].volume + guests[1].volume << endl;
 system("pause");
 return 0;
}

4.4.6 结构中的位字段

字段的类型应为整型或枚举(稍后将介绍),接下来

是冒号,冒号后面是一个数字,它指定了使用的位数。可以使用没有名称的字段来提供间距。每个成员都被称为位字段(bit field)。下面是一个例子:




猜你喜欢

转载自blog.csdn.net/zhangfengfanglzb/article/details/80591388