這是一個(gè)滿足這些需求的結(jié)構(gòu)體描述:
struct Product // structure declaration { char name[20]; float volume; double price; };
關(guān)鍵字struct表示代碼定義了一個(gè)結(jié)構(gòu)體的布局。
標(biāo)識(shí)符Product是此表單的名稱或標(biāo)簽。
這使Product為新類型的名稱。
#include <iostream>
struct Product // structure declaration
{
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
Product guest =
{
"C++", // name value
1.8, // volume value
29.9 // price value
};
Product pal =
{
"Java",
3.1,
32.9
}; // pal is a second variable of type Product
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;
}
上面的代碼生成以下結(jié)果。
以下代碼顯示了如何分配結(jié)構(gòu)體。
#include <iostream>
using namespace std;
struct Product
{
char name[20];
float volume;
double price;
};
int main()
{
Product bouquet = { "C++", 0.20, 12.49 };
Product 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;
return 0;
}
上面的代碼生成以下結(jié)果。
可以創(chuàng)建其元素是結(jié)構(gòu)體的數(shù)組。
例如,要?jiǎng)?chuàng)建一個(gè)100個(gè)產(chǎn)品結(jié)構(gòu)體的數(shù)組,您可以執(zhí)行以下操作:
Product gifts[100]; // array of 100 Product structures cin >> gifts[0].volume; // use volume member of first struct cout << gifts[99].price << endl; // display price member of last struct
要初始化一個(gè)結(jié)構(gòu)體數(shù)組,您將將數(shù)組初始化的規(guī)則與結(jié)構(gòu)體規(guī)則相結(jié)合。
因?yàn)閿?shù)組的每個(gè)元素都是一個(gè)結(jié)構(gòu)體,它的值由結(jié)構(gòu)體初始化表示。
Product guests[2] = // initializing an array of structs { {"A", 0.5, 21.99}, // first structure in array {"B", 2000, 565.99} // next structure in array };
以下代碼顯示了一個(gè)使用結(jié)構(gòu)體數(shù)組的簡(jiǎn)短示例。
#include <iostream>
using namespace std;
struct Product
{
char name[20];
float volume;
double price;
};
int main()
{
Product guests[2] = // initializing an array of structs
{
{"A", 0.5, 21.99}, // first structure in array
{"B", 2, 5.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";
return 0;
}
上面的代碼生成以下結(jié)果。
更多建議: