10.1 结构(结构体、结构数组、结构指针)

结构相当于一种新的数据类型,如int 、 char 、float之类的数据类型,只不过是我们自己定义的,定义的时候不要忘了{}后面的分号。

结构既然是一种变量类型,那就和我们常用的int、char、float等的类型使用原理是一样的。只不过运用的时候表达方式略微有点差距罢了。

   

结构体把很多类型不一样的数据整合在一起了,相当于自己定义了一种新的数据类型,后面可以直接拿来用。

【注意】

1. 结构体变量的大小:各成员变量大小之和。

2. 结构体变量的存储方式:结构变量Student中的各个成员变量unsigned、char、float在内存中一半是连续存放的。

Date birthday: birthday变量中就包含了year、month、day这三个Date的成员变量。

next的类型是Employee *,是一种指针,可以指向自己本身。next可以指向任何Employee类型的变量。

#include<iostream>
#include<cstring>
using namespace std;
struct Date{
	int year;
	int month;
	int day;
}; //注意分号

struct StudentEx{
	unsigned ID;
	char szName[20];
	float fGPA;
	Date birthday;
};

int main()
{
	StudentEx stu;
	cin >> stu.fGPA;//4.5
	stu.ID = 12345;
	strcpy(stu.szName, "Tom");
	cout << stu.fGPA << endl;//4.5
	stu.birthday.year = 1984;//这里要注意一下表达方式 
	unsigned int *p = & stu.ID; 
	cout << stu.szName << endl << *p << endl << stu.birthday.year << endl;//Tome 12345 1984
	return 0;
}

 

#include<iostream>
using namespace std;
struct Date{
	int year;
	int month;
	int day;
}; 

struct StudentEx{
	unsigned ID;
	char szName[20];
	float fGPA;
	Date birthday;
};

StudentEx Myclass[50];//结构数组,StudentEx相当于一种新的变量类型 
int main()
{
	StudentEx Myclass[50] = {
	{1234,"Tom",3.78,{1984,12,28}},
	{1235,"Jack",3.25,{1985,12,23}},
	{1236,"Mary",4.00,{1984,12,21}},
	{1237,"Johe",2.78,{1985,2,28}}} ;// StudentEx不能少 
	cout << Myclass[1].ID << endl;//1235
	cout << Myclass[2].birthday.year << endl;//1984
	int n = Myclass[2].birthday.month;
	cout << n << endl;//12
	cin >> Myclass[0].szName;//lily更新数据 
	cout << Myclass[0].szName << endl;//lily
	return 0;
} 

#include<iostream>
using namespace std;
struct Date{
	int year;
	int month;
	int day;
}; 

struct StudentEx{
	unsigned ID;
	char szName[20];
	float fGPA;
	Date birthday;
};

int main()
{
	StudentEx stu1={12345,"lily",4.83,{1993,12,23}};
	StudentEx *pStudent;
	pStudent = &stu1;//pstudent指向了stu1所在的地址 
	StudentEx stu2 = *pStudent;
	cout << stu2.ID << " " << stu2.szName <<" " << stu2.fGPA << " " << stu2.birthday.year << endl;
	return 0;
 } 

#include<iostream>
using namespace std;
struct Date{
	int year;
	int month;
	int day;
}; 

struct StudentEx{
	unsigned ID;
	char szName[20];
	float fGPA;
	Date birthday;
};

int main()
{
	StudentEx stu;
	StudentEx * pStu;
	pStu = &stu;
	pStu->ID = 12345;
	(*pStu).fGPA = 3.48;
	cout << stu.ID << endl;
	cout << stu.fGPA << endl;
} 

猜你喜欢

转载自blog.csdn.net/yanyanwenmeng/article/details/81218576