C++——结构体

1.定义方法

第一种
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
	string name;
	int age;
	int score;
}s;


第二种
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
	string name;
	int age;
	int score;
}s;

第二种
int main()
{
	struct student s;//c++中struct可省略
	s.name="张三";
    s.age=18;
    s.score=100;
	return 0;
}

第三种
#include<iostream>
#include<cstring>
using namespace std;
struct student
{
	string name;
	int age;
	int score;
};
int main()
{
	struct student s={"张三",18,100};//c++中struct可省略
	
	return 0;
}

2.结构体数组

#include<iostream>
#include<cstring>
using namespace std;
struct student
{
	string name;
	int age;
	int score;
};
int main()
{
	struct student stu[3]=
	{
		{"张三",18,100},
		{"李四",19,99},
		{"王五",20,66}
	};
	
	for(int i=0;i<3;i++)
	{
		cout<<stu[i].name<<" "<<stu[i].age<<" "<<stu[i].score<<"\n";
	}
	return 0;
}

3.结构体指针

->结构体指针访问元素的途径

#include<iostream>
#include<cstring>
using namespace std;
struct student
{
	string name;
	int age;
	int score;
};
int main()
{
	struct student s={"张三",18,100};
	
	struct student * p=&s;
	p->name="李四";
	cout<<s.name<<"\n";
	
	return 0;
}

4.结构体嵌套结构体

结构体可发生多层嵌套(在这里不过多演示,非常简单)

5.结构体做函数参数

#include<iostream>
#include<cstring>
using namespace std;
struct student
{
	string name;
	int age;
	int score;
};
void print1(student s)
{
	s.age=20;
}
void print2(student * s)
{
	s->age=20;
}
int main()
{
	struct student s={"张三",18,100};
	
	//值传递
	print1(s);
	cout<<s.age<<"\n";
	//址传递
	print2(&s);
	cout<<s.age<<"\n";
	
	return 0;
}

6.结构体中const使用场景

#include<iostream>
#include<cstring>
using namespace std;
struct student
{
	string name;
	int age;
	int score;
};
void print2(const student * s)//加const防止函数中的错误操作
{
	//s->age=20;//操作失败,因为加了const修饰
	cout<<s->age<<"\n";
}
int main()
{
	struct student s={"张三",18,100};
	

	print2(&s);
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值