#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
struct Date
{
int year;
int month;
int day;
};
struct Student
{
int num; //学号
string name; //姓名
int score; //成绩
Date birther; //结构体成员可以是另外一个结构体的变量,birther为Date结构体类型的变量
};
int main()
{
/* 结构体的基本用法 */
Student student1 = { 1001,"王大锤",98 ,2000,10,15};
Student student2 = student1;
cout << student1.name << endl;
cout << student2.num << endl;
cout << student2.score << endl;
cout << student1.birther.year << "/" << student1.birther.month << "/" << student1.birther.day << endl;
/* 结构体数组 */
Student student[3] = { {1001,"嘤嘤嘤",98,2000,10,30},
{1002,"喵喵喵",97,1998,12,30},
{1003,"汪汪汪",96,1985,6,6} };
cout << student[0].name << '\t' << student[1].name << '\t' << student[2].name << endl;//结构体数组输出形式
/* 指向结构体变量的指针 */
Student stu;
Student*p = &stu;
(*p).num = 1004; //用指针直接对stu中的num赋值,由于.运算符优先级最高所以得加括号
stu.name = "小李";
stu.score = 88;
stu.birther.year = 1999;
stu.birther.month = 1;
stu.birther.day = 2;
cout << stu.num << '\t' << stu.name << '\t' << (*p).score << '\t' << p->birther.year << endl; // p->birther.year等同于(*p).birtherr.year
/* 应用结构体和指针构成静态链表 */
struct Astu
{
int num;
int score;
Astu *next; //用来指向下一组数据
};
Astu a, b, c, *head, *ptr;
a.num = 01; a.score = 88; //依次赋值
b.num = 02; b.score = 99;
c.num = 03; c.score = 100;
head = &a; //把结点a的起始地址赋值给head
a.next = &b; //把结点b的起始地址赋值给a里面的指针next
b.next = &c; //把结点c的起始地址赋值给b里面的指针next
c.next = NULL; //把最后一个结点的指向设为空
ptr = head;
do
{
cout << ptr->num << '\t' << ptr->score << endl; //输出ptr指向的结点的数据
ptr = ptr->next; //使ptr指向下一个结点
} while (ptr != NULL); //输出完c后ptr指向的结果为NULL则停止执行
/* 结构体作为函数参数使用引用传递地址 */
void print(Student &);//声明输出函数
print(stu);
/* 使用new和delete动态分配和撤销存储空间 */
Date *T;
T = new Date;
T->year = 2018;
T->month = 12;
T->day = 12;
cout << T->year << '\t' << T->month << '\t' << T->day << endl;
delete T;
system("pause");
return 0;
}
void print(Student &stud) //用引用的方式传址输出
{
cout << stud.num << '\t' << stud.name << '\t' << stud.score << endl;
}
C++学习笔记:结构体的一些用法,以及通过结构体和指针搭建的单向静态链表。
最新推荐文章于 2021-10-22 10:34:24 发布