例7.1:定义两个结构体变量student1和student2,初始化并赋值;
#include<iostream>
using namespace std;
struct Date // 声明结构体类型Date
{
int month;
int day;
int year;
};
struct Student //声明结构体类型Student
{
int num;
char name[20];
char sex;
Date birthday; //声明birthday为Date类型成员
float score;
}student1, student2 = { 1002, "WangL", 'f',5,23,1992,89.5 };
int main()
{
student1 = student2;
cout << student1.num << endl;
cout << student1.name << endl;
cout << student1.sex << endl;
cout << student1.birthday.month<<'/'<<student1.birthday.day
<<'/'<<student1.birthday.year<< endl;
cout << student1.score << endl;
return 0;
}
执行效果如图:
例7.2结构体数组的定义和引用:有三个候选人竞选领导10个人投票统计得票数:
#include<iostream>
using namespace std;
struct Person//声明结构体类型Person
{
char name[20];
int count;
};
int main()
{
Person leader[3] = { "Li", 0, "Zhang", 0, "Sun", 0 };/*定义
Person类型的数组,内用为三个候选人的名字和票数*/
int i, j;
char leader_name[20];
for (i = 0; i < 10; i++)
{
cin >> leader_name;
for (j = 0; j < 3; j++)
if (strcmp(leader_name, leader[j].name) == 0)
leader[j].count++;//如果与某一候选人姓名相同就加一票
}
cout << endl;
for (i = 0; i < 3; i++)
{
cout << leader[i].name << ":" << leader[i].count << endl;
}
return 0;
}
执行效果如图:
例7.3,通过指向结构体变量的指针引用结构体变量中的成员;
#include<iostream>
#include<string>
using namespace std;
int main()
{
struct Student//声明结构体类型
{
int num;
string name;
char sex;
float score;
};
Student stu;
Student *p = &stu;//p为指向Student类型数据的指针变量并指向stu
stu.num = 10301;
stu.name = "Wang Fang";
stu.sex = 'f';
stu.score = 89.5;
cout << stu.num << " " << stu.name << " " << stu.sex << " " <<
stu.score << endl;
cout << (*p).num << " " << (*p).name << " " << (*p).sex << " " <<
p->score << endl;
return 0;
}
执行结果如图:
例7.4,建立和输出一个简单的链表:
#define NULL 0//此行可以省略
#include<iostream>
#include<string>
using namespace std;
struct student//声明结构体类型
{
int num;
float score;
struct student *next;
};
int main()
{
student a, b, c, *head, *p;
a.num = 31001; a.score = 89.5;//对节点a的成员赋值
b.num = 31003; b.score = 90;//对节点b的成员赋值
c.num = 31007; c.score = 85;//对节点c的成员赋值
head = &a;//节点a的起始地址赋给头指针head
a.next = &b;
b.next = &c;
c.next = NULL;
p = head;//p指针指向a节点
do
{
cout << p->num << " " << p->score << endl;
p = p->next;//使p指向下一个节点
} while (p != NULL);
return 0;
}