首页 > 编程语言 > 详细

c++基础--结构体

时间:2021-06-01 14:54:54      阅读:15      评论:0      收藏:0      [点我收藏+]

结构体

1.结构体的定义

结构体是一种自定义数据类型,允许用户存储不同的数据类型

struct 结构体名字 {结构体成员列表}

通过结构体创建变量的方式有三种

struct student
{
	string name;
	int age;
	int score;
}s3;//第三种
int main() {
	//创建学生
	//struct关键字可以省略 创建变量时可以省略
	//1.struct student s1
	struct student s1;
	s1.name = "小王";
	s1.age = 777;
	s1.score = 0;
	//2.struct student s2={....}
	struct student s2 = { "小明",22,89 };
	//3.在定义结构体时创建结构体变量
	s3.age = 30;
	s3.name = "老王";
	s3.score = 90;

	system("pause");
	return 0;
}

2.结构体数组

//1.创建结构体
struct student {
	string name;
	int age;
	int score;
};
int main() {
	//语法 struct 结构体名称 数组名[元素个数]={ }

	//2.创建结构体数组
	struct student arr[3] = 
    {
		{"小王",20,90},
		{"老王",34,34},
		{"小三",899,99},
	};
	//3.赋值
	arr[1].name = "张三";
	//4.遍历结构体
	for (int i = 0; i < 3; i++)
	{
		cout << arr[i].name << arr[i].age << arr[i].score << endl;
	}
	system("pause");
	return 0;
}

3.结构体指针

struct student {
	string name;
	int age;
	int score;
};
int main() {
	//1.创建结构体变量
	student s1 = { "小王",67,7837 };

	//2.指针指向
	student* p = &s1;

	//3.访问 p->
	cout << p->name << endl;


	system("pause");
	return 0;
}

4.结构体嵌套

struct student
{
	string name;
	int age;
	int score;

};
struct teacher
{
	string name;
	int age;
	int number;
	struct student s;//嵌套

};
int main() {
	teacher t;
	t.age = 90;
	t.name = "小王";
	t.number = 110;
	t.s.name = "老王";//学生的名字赋值
	cout << t.s.name << endl;

	system("pause");
	return 0;
}

5.结构体做函数参数

struct student {
	string name;
	int age;
	int score;
};
//值传递
void printstudent1(struct student s) {
	s.name = "小王";
	 cout << "子函数中打印" << "s.name=" << s.name << " s.age=" << s.age << " s.score=" << s.score << endl;
};
//地址传递
void printstudent2(struct student* p) {
	p->name = "小王";
	cout << "子函数中打印" << "s.name=" << p->name << " s.age=" << p->age << " s.score=" << p->score << endl;
};
int main() {
	struct student s;
	s.name = "崔鑫";
	s.age = 12;
	s.score = 90;
	//printstudent1(s);//值传递
	printstudent2(&s);//地址传递
	cout << "main函数中打印" << "s.name=" << s.name << " s.age=" << s.age << " s.score=" << s.score << endl;

	system("pause");
	return 0;
}

6.const使用场景

与const修饰指针一样 防止误操作

const student *s

c++基础--结构体

原文:https://www.cnblogs.com/panq/p/14836524.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!