C++学习笔记:结构体的一些用法,以及通过结构体和指针搭建的单向静态链表。

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值