struct BookInfo { string title; string author; string publisher; double price; };以下語句定義了一個名為 bookList 的陣列,它有 20 個元素,每個元素都是一個 BookInfo 結構體。
BookInfo bookList[20];
陣列中的每個元素都可以通過下標來存取。例如,bookList[0] 是陣列中的第一個結構體,bookList[1] 是第二個結構體,依此類推。bookList[5].title
以下迴圈遍歷陣列,顯示儲存在每個元素中的資訊:for (int index = 0; index < 20; index++) { cout << bookList[index].title << endl; cout << bookList[index].author << endl; cout << bookList[index].publisher << endl; cout << bookList[index].price << endl << endl; }因為成員 title、author 和 publisher 都是 string 物件,所以組成字串的各個字元也可以被存取。以下語句顯示 bookList [10] 的 title 成員的第一個字元:
cout << bookList[10].title[0];
以下語句可將字元 t 儲存在 bookList[2] 的 publisher 成員的第 4 個位置。bookList[2].publisher[3] ='t';
下面的程式將計算和顯示一組員工的收入資訊,它使用了一個單一的結構體陣列:// This program uses an array of structures to hold payroll data. #include <iostream> #include <iomanip> using namespace std; struct PayInfo // Define a structure that holds 2 variables { int hours; // Hours worked double payRate; // Hourly pay rate }; int main () { const int NUM_EMPS = 3; // Number of employees PayInfo workers[NUM_EMPS];// Define an array of Paylnfo structures double grossPay; // Get payroll data cout << "Enter the hours worked and hourly pay rates of "<< NUM_EMPS << " employees. n"; for (int index = 0; index < NUM_EMPS; index++) { cout << "nHours worked by employee #" << (index + 1) << ":"; cin >> workers[index].hours; cout << "Hourly pay rate for this employee: $"; cin >> workers[index].payRate; } // Display each employeef s gross pay cout << "nHere is the gross pay for each employee:n"; cout << fixed << showpoint << setprecision(2); for (int index = 0; index < NUM_EMPS; index++) { grossPay = workers[index].hours * workers[index].payRate; cout << "Employee #" << (index + 1); cout << ": $" << setw(7) << grossPay << endl; } return 0; }程式輸出結果:
Enter the hours worked and hourly pay rates of 3 employees.
Hours worked by employee #1:10
Hourly pay rate for this employee: $9.75
Hours worked by employee #2:15
Hourly pay rate for this employee: $8.65
Hours worked by employee #3:20
Hourly pay rate for this employee: $10.50
Here is the gross pay for each employee:
Employee #1: $ 97.50
Employee #2: $ 129.75
Employee #3: $ 210.00
struct PayInfo { int hours; //己工作的小時數 double payRate; // 每小時收入 PayInfo (int h = 0, double p = 0.0) // 建構函式 { hours = h; payRate = p; } };使用這個結構體宣告,原程式中的陣列現在可以初始化如下:
PayInfo workers[NUM_EMPS] = { PayInfo(10, 9.75),PayInfo(15, 8.65),PayInfo(20, 10.50)};
請注意,初始化結構體陣列中的成員的語法與初始化物件陣列中的成員的語法相同。這與初始化單個結構體的語法不同。