C++结构体

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

// 结构体语法: struct 结构体名称 { 结构体成员列表 }
// 自定义数据类型 一些类型集合组成的一个类型
struct student
{
	string name;//姓名
	int age;//年龄
	int score;//分数
}s3; //顺便创建结构体变量

struct teacher {
	int id;//职工编号
	string name;//姓名
	int age;//年龄
	student student;//学生  (结构体嵌套结构体)
};

//打印结构体
//值传递
void printStruct(student s)
{
	s.age = 30;
	cout << s.name << endl << s.age << endl << s.score << endl;
}

//地址传递
void printStruct2(student *s)
{
	s->age = 30;
	//cout << (*s).name << endl << (*s).age << endl << (*s).score << endl;
	cout << s->name << endl << s->age << endl << s->score << endl;
}

//  如果不想修改主函数中的教据,用值传递,反之用地址传递

int main()
{
	// struct关键字可以省略
	//struct student s1;
	student s1;

	s1.name = "Mike";
	s1.age = 18;
	s1.score = 95;
	cout << s1.name << endl << s1.age << endl << s1.score << endl;
	cout << "----------------" << endl;

	student s2 = { "Andy",17,100 };
	cout << s2.name << endl << s2.age << endl << s2.score << endl;
	cout << "----------------" << endl;

	s3.name = "YOYO";
	s3.age = 19;
	s3.score = 90;
	cout << s3.name << endl << s3.age << endl << s3.score << endl;
	cout << "----------------" << endl;

	// 结构体数组
	student arr[] = {
		{"张三",18,85},
		{"李四",19,100},
		{"王五",20,95}
	};
	
	/*int len = sizeof(arr) / sizeof(arr[0]);
	printarr(arr, len);*/
	for (int i = 0; i < 3; i++)
	{
		cout << arr[i].name << endl << arr[i].age << endl << arr[i].score << endl;
	}
	cout << "----------------" << endl;

	student s4 = { "小明",25,60 };
	student *s5 = &s4;

	cout << "姓名:" << s5->name << endl << "年龄:" << s5->age << endl << "分数:" << s5->score << endl;

	cout << "----------------" << endl;

	teacher t1 = {
		123,"王老师",35,{"李华",18,93}
	};

	cout << "id:" << t1.id << endl << "姓名:" << t1.name << endl << "年龄:" << t1.age 
		<< endl << "学生:" << t1.student.name << "," << t1.student.age << "," << t1.student.score << endl;

	cout << "----------------" << endl;

	//printStruct(s4);

	printStruct2(&s4);

	cout << s4.name << endl << s4.age << endl << s4.score << endl;


	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值