c++结构体

#include<iostream> 
using namespace std;
#include<string> 

int main(){
	//结构体 
	/*
	结构体属于用户自定义的数据类型,允许用户存储不同的
	数据类型。
	
	结构体的定义和使用:
	struct 结构体名{结构体成员列表} ;
	通过结构体创建变量的方式有三种:
	1、struct结构体名 变量名
	2、struct结构体名 变量名 = {成员1值,成员2值...}
	3、定义结构体时顺便创建变量 
	*/ 
	//结构体定义
	struct student
	{
		//成员列表
		string name;//姓名
		int age;//年龄
		int score;//分数 
	 } s3 ; //3、 在定义结构体时顺便创建结构体变量 
	 s3.name = "小明";
	 s3.age = 21;
	 s3.score = 21;
	 cout << s3.name << endl;
	 cout << s3.age << endl;
	 cout << s3.score << endl;
	 /*
	 输出结果:
	 	小明
		21
		21	 
	 */
	 
	 //通过学生类型创建具体的学生
	 //1、struct student s1  (struct关键字可省略) 
	 struct student s1;
	 s1.name = "张三";
	 s1.age = 12;
	 s1.score = 98;
	 
	 cout << s1.name << endl;
	 cout << s1.age << endl;
	 cout << s1.score << endl;
	 /*
	 	输出结果:
		 张三
		 12
		 98 
	 */
	 
	 //2、struct student s2={...}
	 struct student s2 = {
	 	"李四",14,100
	 }; 
	cout << s2.name << endl;
	cout << s2.age << endl;
	cout << s2.score << endl;
	/*
	输出结果:
	李四
	14
	100 
	*/
	
}
#include <iostream>
using namespace std;
#include<string>

//结构体数组
// 1、定义结构体
struct Student{
	string name;
	int age;
	int score;
};

int main(){
	// 2、创建结构体数组
	struct Student stuArry[3] = {
		{"张三",18,100
		},
		{"李四",10,89
		},
		{"王五",44,12
		}
	};
	//3、给结构体数组中的元素赋值
	stuArry[2].name = "小明";
	stuArry[2].age = 56;
	stuArry[2].score = 22;
	//4、遍历结构体数组 
	for(int i=0;i<3;i++){
		cout << "姓名"<<stuArry[i].name<< endl; 
		cout << "年龄"<<stuArry[i].age<< endl; 
		cout << "分数"<<stuArry[i].score<< endl; 
	}
	/*
	输出结果:
	姓名张三
	年龄18
	分数100
	姓名李四
	年龄10
	分数89
	姓名小明
	年龄56
	分数22 
	*/
}
#include <iostream>
using namespace std;
#include<string>


//结构体指针 
struct Student{
	string name;
	int age;
	int score;
}; 
int main(){
	//创建学生结构体变量
	struct Student s = {"张三",18,56
	};
	//通过指针指向结构体变量 
	struct Student * p = &s;//struct 可省略 
	//通过指针访问结构体变量中的数据 利用箭头访问属性 
	cout << "姓名" << p->name << p->age << p->score << endl; 
	/*
	输出结果:
	姓名张三1856 
	*/
} 
#include <iostream>
using namespace std;
#include<string>

//结构体嵌套结构体
//作用:结构体中的成员可以是另一个结构体
//例如:每个老师辅导一个学员,一个老师的结构体中,记录一个
//学生的结构体

//学生结构体定义
struct student{
	//成员列表
	string name;
	int age;
	int score; 
}; 

//教师结构体定义
struct teacher{
	//成员列表
	int id;
	string name;
	int age;
	struct student stu;//子结构体 学生 
}; 
int main(){
	//创建老师
	teacher t;
	t.id=77777;
	t.name="li";
	t.age=28;
	t.stu.name="小明";
	t.stu.age=18;
	t.stu.score=66;
	
	cout <<"老师姓名"<<t.name <<"老师编号"<<t.id<<endl;
	cout<< "老师年龄"<<t.age<< endl;\
	cout<<"老师辅导学生"<<t.stu.name<<t.stu.age<<t.stu.score<< endl;
	/*
	输出结果:
	老师姓名li老师编号77777
	老师年龄28
	老师辅导学生小明1866 
	*/
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值