C++--结构体

1、结构体基本概念

结构体属于用户自定义的数据类型,允许用户存储不同类型的数据。

2、结构体定义和使用

语法:struct (结构体变量名) {成员列表}

结构体的创建方式有三种

  • struct  结构体 变量名
  • struct 结构体 变量名={.....}
  • 在定义结构体的时候顺便创建变量

示例:

// 1、结构体定义
struct Student
{
	//成员列表
	string name; //姓名
	int age;    //年龄
	float score; // 分数
} stu3; // 第三种创建方式

int main()
{
	
    // 结构体创建方式1
	struct Student s1;
	s1.age = 18;
	s1.name = "zhaosi";
	s1.score = 100;
    // 结构体创建方式2
	struct Student s2 = { "lisi",19,87 };
	// 第三种 

}

3、结构体数组

结构体数组:将用户自定义的结构体变量放到数组中,便于维护

语法:struct (数组名[元素个数])={{},{},.....{}}

示例:

#include<iostream>
#include<string>
using namespace std;
struct Student
{
	string name;
	int age;
	float score;
};
int main()
{
	// 创建结构体数组
	Student arr[3] = {
		{"zhangsan",18,50.8},
		{"lisi",    19,78},
		{"wangwu",20,100}
	};
	// 修改结构体数组中元素值
	arr[2].name = "zhailou";

	// 遍历结构体数组
	for (int i = 0; i < 3; i++)
	{
		cout << "姓名:" << arr[i].name <<"  " 
			<< "年龄 :" <<arr[i].age <<"  " 
			<< "成绩:" << arr[i].score << endl;
 	}
}

4、结构体指针

通过指针访问结构体中的成员。

示例:

#include<iostream>
#include<string>
using namespace std;
//结构体定义
struct Student
{
	//成员列表
	int age;   //年龄
	string  name; // 姓名
	float score;  // 分数
};
int main()
{
	// 创建结构体变量
	Student s1 = { 18,"Wangwu",78.9 };
	// 创建指针指向结构体变量
	Student* p = &s1;
	// 访问结构体变量中的数据
	// 通过指针访问结构体需要用->符号
	cout << "姓名:" << p->name << "年龄:" << p->age << "分数:" << p->score;
}

5、结构体嵌套结构体

作用:结构体中的成员是另一个结构体

#include<iostream>
#include<string>
using namespace std;
//学生结构体定义
struct Student
{
	//成员列表
	int age;   //年龄
	string  name; // 姓名
	float score;  // 分数
};
// 教师结构体定义
struct Teacher {
	// 成员列表
	int  id; // 职工编号
	string name; //教师姓名
	int age; //教师年纪
	struct Student s1;//指导的学生 子结构体
};
int main()
{
	// 创建结构体变量
	Student s1 = { 18,"Wangwu",78.9 };
	Teacher t1 = { 2,"Zhu",78,s1 };
	// 创建指针指向结构体变量
	Teacher* p = &t1;
	// 访问结构体变量中的数据
	// 通过指针访问结构体需要用->符号
	cout << "姓名:" << p->name << "年龄:" << p->age << "分数:" << p->s1.score;
}

6、结构体做函数参数

作用:将结构体作为参数向函数中传递

传递方式:

  • 值传递
  • 地址传递
    // 1、结构体定义
    struct Student
    {
    	//成员列表
    	string name;
    	int age;
    	float score;
    };
    // 值传递
    void printStruct(struct Student s)
    {
    	cout << s.name<<endl;
    	cout << s.age << endl;
    	cout << s.score << endl;
    
    }
    // 地址传递
    void printStruct2(struct Student* p)
    {
    	p->age = 100;
    	cout << p->name << endl;
    	cout << p->age << endl;
    	cout << p->score<< endl;
    }
    int main()
    {
    
    	struct Student s1;
    	s1.age = 18;
    	s1.name = "zhaosi";
    	s1.score = 100;
    	struct Student s2 = { "lisi",19,87 };
    	printStruct2(&s2);
    	printStruct(s2);
    
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值