结构是不同数据类型的项目的集合。在创建具有不同数据类型记录的复杂数据结构时非常有用。使用struct关键字定义结构。
结构的示例如下-
struct employee {
int empID;
char name[50];
float salary;
};使用结构存储和显示信息的程序如下。
#include <iostream>
using namespace std;
struct employee {
int empID;
char name[50];
int salary;
char department[50];
};
int main() {
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } };
cout<<"员工信息如下:"<<endl;
cout<<endl;
for(int i=0; i<3;i++) {
cout<<"Employee ID: "<<emp[i].empID<<endl;
cout<<"Name: "<<emp[i].name<<endl;
cout<<"Salary: "<<emp[i].salary<<endl;
cout<<"Department: "<<emp[i].department<<endl;
cout<<endl;
}
return 0;
}输出结果
员工信息如下: Employee ID: 1 Name: Harry Salary: 20000 Department: Finance Employee ID: 2 Name: Sally Salary: 50000 Department: HR Employee ID: 3 Name: John Salary: 15000 Department: Technical
在上述程序中,结构是在main()方法之前定义的。该结构包含员工ID,员工姓名,工资和部门。下面的代码片段对此进行了演示。
struct employee {
int empID;
char name[50];
int salary;
char department[50];
};在该main()函数中,定义了struct employee类型的对象数组。其中包含员工ID,姓名,薪水和部门值。如下所示。
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } };使用for循环显示结构值。以下列方式显示。
cout<<"员工信息如下:"<<endl;
cout<<endl;
for(int i=0; i<3;i++) {
cout<<"Employee ID: "<<emp[i].empID<<endl;
cout<<"Name: "<<emp[i].name<<endl;
cout<<"Salary: "<<emp[i].salary<<endl;
cout<<"Department: "<<emp[i].department<<endl;
cout<<endl;
}