栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

自学C++之结构体的定义和使用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自学C++之结构体的定义和使用

注意事项

1、定义结构体时的关键字struct不能省略

2、创建结构体的函数变量的时候,struct可以省略

3、结构体变量,利用操作符"."访问成员

定义结构体有三种方法

1、struct Student s1

2、struct Student s2={赋初值}

3、在定义结构体的时候,顺便创建结构体变量

#include 
#include
using namespace std;

//创建学生数据类型
//自定义数据类型,一些类型的集合组成的类型
//语法:struct 类型名 {成员列表}
//定义函数的时候,struct不能省略
struct Student
{
	//成员列表

	//姓名
	string name;
	//年龄
	int age;
	//分数
	int score;
}s3;//定义s3直接就能用来定义了

//通过学生数据类型创建就具体的学生
//1、struct Student s1
//2、struct Student s2={赋初值
//3、在定义结构体的时候,顺便创建结构体变量}


int main()
{
	cout << "*****************************" << endl;
	//1、struct Student s1
	struct Student s1;
	s1.name = "张三";
	s1.age = 18;
	s1.score = 99;
	cout << "姓名:" << s1.name << endl;
	cout << "年龄:" << s1.age << endl;
	cout << "成绩:" << s1.score << endl;
	cout << "*****************************" << endl;
	//在C++,创建变量的时候,struct 这个关键字可以省略
	Student s4;
	s4.name = "漂亮小姐姐";
	s4.age = 19;
	s4.score = 99;
	cout << "姓名:" << s4.name << endl;
	cout << "年龄:" << s4.age << endl;
	cout << "成绩:" << s4.score << endl;
	cout << "*****************************" << endl;
	//2、struct Student s2={赋初值
	struct Student s2 = { "李四",19,66 };
	cout << "姓名:" << s2.name << endl;
	cout << "年龄:" << s2.age << endl;
	cout << "成绩:" << s2.score << endl;
	cout << "*****************************" << endl;
	//3、在定义结构体的时候,顺便创建结构体变量}
	s3.name = "王五";
	s3.age = 18;
	s3.score = 18;
	cout << "姓名:" << s3.name << endl;
	cout << "年龄:" << s3.age << endl;
	cout << "成绩:" << s3.score << endl;
	cout << "*****************************" << endl;


	system("pause");
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/921091.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号