C语言中的数组pay,C++结构体数组(无师自通)

数组元素也可以是结构体。当程序员想要存储一个包含多个数据字段的记录集但又不想使用对象时,这是很有用的。

因为结构体可以容纳多个不同数据类型的项目,所以可以使用单个结构体数组来代替几个常规变量数组。

结构体数组可以像其他数组一样定义。假设程序中存在以下结构声明:

struct BookInfo {

string title;

string author;

string publisher;

double price;

};

以下语句定义了一个名为 bookList 的数组,它有 20 个元素,每个元素都是一个 BookInfo 结构体。

BookInfo bookList[20];

数组中的每个元素都可以通过下标来访问。例如,bookList[0] 是数组中的第一个结构体,bookList[1] 是第二个结构体,依此类推。

因为结构体的成员默认是公共的,所以不需要像使用类对象一样使用一个函数来访问它们,而是可以通过简单地将点运算符和成员名称放在下标后面来访问任何元素的成员。

例如,下面的表达式引用了 bookList[5] 的 title 成员:

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

#include

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)};

请注意,初始化结构体数组中的成员的语法与初始化对象数组中的成员的语法相同。这与初始化单个结构体的语法不同。

你可能感兴趣的:(C语言中的数组pay)