structure.cpp: a simple structure
#include <iostream> struct inflatable { char name[20]; float volume; double price; }; int main() { using namespace std; inflatable guest = { "Glorious Gloria", 1.88, 29.99 }; inflatable pal = { "Audacious Arthur", 3.12, 32.99 }; cout << "Expand your guest list with " << guest.name; cout << " and " << pal.name << "!\n"; cout << "You can have both for $"; cout << guest.price + pal.price << "!\n"; return 0; }
1. 编译输出:
Expand your guest list with Glorious Gloria and Audacious Arthur! You can have both for $62.98!
2. 代码详解:
结构可以存储多种类型的数据,而数组只能存储形同类型的数据。
结构是用户定义的类型,而结构声明定义了这种类型的数据属性。
首先,定义结构描述:描述并标记了能够存储在结构中的各种数据类型。
然后,按描述创建结构变量(结构数据对象)。
关键字struct定义了一个结构布局,标识符inflatable是此数据格式的名称。大括号中包含的是结构存储的数据类型的列表,其中每个列表都是一条声明语句。列表中的每一项都被称为结构成员。
C++允许在声明结构变量时省略关键字struct。
通过成员名能够访问结构的成员,就像通过索引能够访问数组的元素一样。
如pal.price,pal是一个结构,pal.price是一个double变量。
位于函数外面的声明被称为外部声明。通常应使用外部声明,使得所有函数都可以使用此类型的结构。外部声明即将声明放到mian()的前面。
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; cout << "choice: " << choice.name << " for $"; cout << choice.price << endl; return 0; }
1. 编译输出:
bouquet: sunflowers for $12.49 choice: sunflowers for $12.49
2. 代码详解:
成员赋值(memberwise assignment):使用赋值运算符将结构赋给另一个同类型的结构。
定义结构和创建结构变量
struct perks { int key_number; char car[12]; } mr_smith, ms_jones;
定义结构、创建结构并初始化
struct perks { int key_number; char car[12]; } mr_glitz = { 7, "Packard" };
将结构定义和变量声明分开,可以使程序更易于阅读和理解。
arrstruct.cpp: an array of structures
#include <iostream> struct inflatable { char name[20]; float volume; double price; }; int main() { using namespace std; inflatable guests[2] = { {"Bambi", 0.5, 21.99}, {"Godzilla", 2000, 565.99} }; cout << "The guests " << guests[0].name << " and " << guests[1].name << "\nhave a combined volume of " << guests[0].volume + guests[1].volume << " cubic feet.\n"; return 0; }
1. 编译输出:
The guests Bambi and Godzilla have a combined volume of 2000.5 cubic feet.
2. 代码详解:
结构数组:guests是一个inflatable数组,其中的每个元素都是inflatable对象。
初始化结构数组:使用大括号包括一个大括号进行初始赋值。
联系客服