结构体相关内容

1.结构体

#include <iostream>
#include <string>//注意要加字符串的头文件
using namespace std;
//结构体 struct 结构体 {结构体成员列表};
//创建一个学生类型
struct Student //要在头文件和命名定义完后写才是有效的
{
	string name;//char是字符,string是字符串
	int age;
	int score;
}s3;
//通过学生类型创建具体的学生
/*
通过结构体创建变量的方式:
struct结构体名 变量名
struct结构体名 变量名 = {成员1值,成员2值...}
定义结构体时顺便创建变量
*/

int main()
{
	//1.struct结构体名 变量名
	//结构体变量创建时关键字可以省略,但结构体定义时不可以省略
	 Student s1;
	//给s1属性赋值
	s1.name = "张三";//通过点访问结构体变量中的属性
	s1.age = 21;
	s1.score = 100;
	cout <<"姓名:"<<s1.name << "   年龄:" << s1.age << "   成绩:" << s1.score << endl;
	//2.struct结构体名 变量名 = {成员1值,成员2值...}
	struct Student s2 = {"李四",19,95};//没赋值的时候会报警告
	cout << "姓名:" << s2.name << "   年龄:" << s2.age << "   成绩:" << s2.score << endl;
	//3.定义结构体时顺便创建变量
	s3.name = "王五";
	s3.age = 20;
	s3.score = 80;
	cout << "姓名:" << s3.name << "   年龄:" << s3.age << "   成绩:" << s3.score << endl;
	system("pause");
	return 0;
}
//结构体变量 属性 对象

2.结构体数组

//结构体数组
#include <iostream>
using namespace std;
#include <string>
struct Student
{
	string name;
	int age;
	int score;
};

int main()
{
	struct Student stuArray[3] =
	{
		{"张三",18,100},
		{"李四",28,99}
	};
	//stuArray[2].name = "王五";
	//stuArray[2].age = 30;
	//stuArray[2].score = 97;
	stuArray[2] = {"王五",30,97};
	for (int i = 0; i < 3; i++)
	{
		//允许换行操作,会更工整
		cout << "姓名:" << stuArray[i].name 
			<< "年龄:" << stuArray[i].age 
			<< "分数:" << stuArray[i].score << endl;
	
	}
	system("pause");
	return 0;
}

3.结构体指针

#include <iostream>
using namespace std;
#include <string>
struct Student
{
	string name;
	int age;
	int score;
};
int main()
{
	//1.创建学生结构体变量
	struct Student s = {"张三",18,100};
	//2.通过指针指向结构体变量
	struct Student * p = &s;
	//3.通过指针访问结构体变量中的数据
	cout << "姓名:" << p->name << "   年龄:" << p->age << "   分数:" << p->score << endl;
	system("pause");
	return 0;
}

4.结构体做函数参数

#include <iostream>
using namespace std;
#include <string>
struct Student
{
	string name;
	int age;
	int score;
};
void Printf(struct Student s)//值传递 形参变实参不变
{
	cout << "姓名:" << s.name << "   年龄:" << s.age << "   成绩:" << s.score << endl;

};
void Printf2(struct Student * s)//地址传递
{

	cout << "姓名:" << s->name << "   年龄:" << s->age << "   成绩:" << s->score << endl;
};
int main()
{
	Student s = {"张三",18,100};
	//cout << "姓名:" << s.name << "   年龄:" << s.age << "   成绩:" << s.score << endl;
	Printf(s);//值传递
	Printf2(&s);//地址传递
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值