C++结构体讲解
1.结构体定义
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;
}s3; //3.
// 创建方式
//1. struct Student s1
//2. struct Studentf s2={...}
//3.在定义结构体时顺便创建结构体变量
int main()
{
//1.
struct Student s1;
s1.name="玛卡巴卡";
s1.age=100;
cout <<"姓名:"<<s1.name<<"年龄:"<<s1.age<<endl;
//2.
struct Student s2={"乌西迪西",1000};
cout <<"姓名:"<<s2.name<<"年龄:"<<s2.age<<endl;
//3.
s3.name="不知道取什么啦";
s3.age=0;
cout <<"姓名:"<<s3.name<<"年龄:"<<s3.age<<endl;
}
struct 关键字在创建时可以省略
2.结构体数组
#include <iostream>
#include <string>
using namespace std;
//1.定义结构体
struct Student
{
string name;
int age;
int score;
};
int main()
{
//2.创建结构体数组
struct Student stuArray[2]=
{
{"Lisa",18,100},
{"Rose",20,100}
};
//3.给结构体数组中元素赋值
stuArray[2].score=99;
//4.遍历结构体数组
for(int i=0;i<3;i++)
{
cout<<"姓名:"<<stuArray[i].name
<<"年龄:"<<stuArray[i].age
<<"分数:"<<stuArray[i].score<<endl;
}
}
3.结构体指针
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
int score;
};
int main()
{
//创建学生结构体变量
struct student s={"张三",18,100};
//通过指针指向结构体变量
student *p =&s;
//通过指针访问结构体变量中的数据
cout<<"姓名:"<<p->name<<" 年龄:"<<p->age<<" 分数:"<<p->score<<endl;
system("pause");
return 0;
}
嵌套结构体
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
int score;
};
struct teacher
{
int id;
string name;
int age;
student stu;
};
int main()
{
teacher t;
t.id=100000;
t.name="老王";
t.age=50;
t.stu.name="小王";
t.stu.age=10;
t.stu.score=99;
system("pause");
return 0;
}
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void pS1(student s);
void pS2(student *p);
int main()
{
struct student s={"张三",18,99};
//结构体做函数参数
//将学生传入到一个参数,打印学生身上的所以信息
pS1(s);
cout<<"改后年龄1:"<<s.age<<endl;
//此时改变形参无法影响到实参
pS2(&s);
cout<<"改后年龄2:"<<s.age<<endl;
//传递地址的方法能够影响实参
system("pause");
return 0;
}
//打印学生信息
//1.值传递
void pS1(student s)
{
s.age=100;
cout<<"1:"<<" 姓名:"<<s.name<<" 年龄:"<<s.age<<" 分数:"<<s.score<<endl;
}
//2.地址传递
void pS2(student *p)
{
p->age=200;
cout<<"2:"<<" 姓名:"<<p->name<<" 年龄:"<<p->age<<" 分数:"<<p->score<<endl;
}
//总结:
//如果不想修改主函数中的数据,用值传递
//反之,用地址传递
const的使用场景
#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void pS(const student *p);
int main()
{
struct student s={"张三",18,99};
pS(&s);
system("pause");
return 0;
}
//2.地址传递
void pS(const student *p)
{
//p->age=200;
//操作失误,因为加了const修饰
cout<<"2:"<<" 姓名:"<<p->name<<" 年龄:"<<p->age<<" 分数:"<<p->score<<endl;
}