《C++ Primer Plus》 第四章 复合类型 Part 3——结构
结构是一种比数组更灵活的数据格式。同一个结构可以储存多种类型的数据,从而将数据的表示合并到一起。
结构声明:
struct Players//标记为新类型的名称
{
int hight;
int weight;
int age;
double kda;
string name;
char gender;//结构中的六个成员
};//结束时用;结尾
创建新建的类型的变量&结构的初始化:
struct Players Bob //C stytle
Players Amy; //C++ stytle
struct Players Bob = {
178, //height
70, //weight
26, //age
9.6, //kda
"Bob", //name
'M' //gender
};
Players Amy{ 170, 60, 25, 8.6, "Amy", 'W' };
Players Dan = {};
Players Alex = { 175 };
和数组的声明和初始化类似,等号是可选的,如果大括号内没有任何内容,各个成员设置为0(字符串为空字符串)。
在程序中使用结构
// structur.cpp -- a simple structure
#include <iostream>
struct inflatable // structure declaration
{
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
inflatable guest =
{
"Glorious Gloria", // name value
1.88, // volume value
29.99 // price value
}; // guest is a structure variable of type inflatable
// It's initialized to the indicated values
inflatable pal =
{
"Audacious Arthur",
3.12,
32.99
}; // pal is a second variable of type inflatable
// NOTE: some implementations require using
// static inflatable guest =
cout << "Expand your guest list with " << guest.name;
cout << " and " << pal.name << "!\n";
// pal.name is the name member of the pal variable
cout << "You can have both for $";
cout << guest.price + pal.price << "!\n";
// cin.get();
return 0;
}
C++通过xxx.xxx
使用结构中的成员。C++将每个结构成员看作是一个相应类型的变量,可以进行相应类型变量可以进行的所有操作。
C++不提倡使用外部变量,但提倡使用外部结构声明。
其他结构属性
赋值
// assgn_st.cpp -- assigning structures
#include <iostream>
struct inflatable
{
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
inflatable bouquet =
{
"sunflowers",
0.20,
12.49
};
inflatable choice;
cout << "bouquet: " << bouquet.name << " for $";
cout << bouquet.price << endl;
choice = bouquet; // assign one structure to another
cout << "choice: " << choice.name << " for $";
cout << choice.price << endl;
// cin.get();
return 0;
}
C++允许将一个结构变量赋值给另一个结构变量。此时,结构中的每一个成员都分别赋值。
声明,创建新成员和初始化
下面这些语句都是合法的,但不建议使用。
- 在声明结构时创建两个结构变量。
- 在声明结构时创建结构变量并声明。
- 声明没有名称的结构。
- 此时可以使用Position1、Position2、Position3三个结构变量。
- 但无法创建新的结构变量。
struct perks1 {
int key_number;
char car[12];
}mr_smith, ms_jones;
struct perks2 {
int key_number;
char car[12];
}
mr_glitz = {7, "Packard"},
ms_smith = {4, "BWM"};
struct {
int x, y;
char ch;
}Position1, Position2,
Position3 = {1, 3, 'M'};
结构与数组
结构中可以包含数组成员,也可以创建元素为结构的数组。
- 结构中包含数组成员时,将按照从上到下,数组下标从小到大赋值。
// arrstruc.cpp -- an array of structures
#include <iostream>
struct inflatable
{
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
inflatable guests[2] = // initializing an array of structs
{
{"Bambi", 0.5, 21.99}, // first structure in array
{"Godzilla", 2000, 565.99} // next structure in array
};
cout << "The guests " << guests[0].name << " and " << guests[1].name
<< "\nhave a combined volume of "
<< guests[0].volume + guests[1].volume << " cubic feet.\n";
// cin.get();
return 0;
}