虽然数组可以存储多个元素,但所有元素类型必须相同,即一个数组可以存储20个元素int,另一个数组可以存储10个float,但同一个数组不能存储在一个元素中int,存储在其他元素中float。cpp由于同一结构可以存储多种类型的数据,因此中间结构可以满足要求,结构比数组更灵活。结构也是cpp OOP类的基石。结构是用户定义的类型,结构声明定义了该类型的数据属性。定义类型后,可以创建该类型的变量。因此,创建结构包括两个步骤。首先,定义结构描述,描述并标记可以存储在数据中的各种数据类型。然后根据描述创建结构变量(结构数据对象)。
struct inflatable { char name[20]; float volume; double price; }
关键字struct这表明这些代码定义了结构布局。标识符inflatable这种数据格式的名称,所以新类型的名称是inflatable。就像创造一样char或int创建类型变量inflatable类型变量。大括号包含结构存储的数据类型列表,每个列表项都是声明语句。这个例子使用了一个适合存储字符串的例子char数组,一个float和一个double。因此,列表中的每一项都被称为结构成员inflatable有3个成员。
这种类型的变量可以在定义结构后创建:
inflatable hat; inflatable woopie_cushion; inflatable maingrame;
由于hat的类型为inflatable,因此可以使用成员运算符.访问所有成员。例如,hat.volume指结构volume成员,hat.price指的是price成员。能够通过成员名访问结构的成员,就像能够通过索引访问数组的元素一样。
// 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; }
和数组一样,cpp11还支持在结构中初始化列表,=是可选的:
inflatable duck{"Daphne",0.12,9.99} inflatable mayor {};
cpp用户类型尽可能与内置类型相似。例如,结构可以作为参数传递给函数,函数也可以返回到结构。此外,赋值运算符也可以使用(=)将结构赋予另一种相同类型的结构,即使成员是数组,也将结构中的每个成员设置为另一种结构中相应成员的值。这种赋值被称为成员赋值。
// 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; }
inflatable结构包含一个数组,也可以以元素为结构的数组,与创建基本类型的数组完全相同。例如,创建一个包含100个的数组inflatable结构的数组
inflatable gifts[100];
gifts它本身就是一个数组,而不是结构。