#include<iostream>#include<string>usingnamespace std;struct People
{//string name;//一些编译器设置string name;在初始化时会崩溃char name[20]="小张";int age=1;int phone=23;}s1;//第1种创建结构体变量的方法intmain(){struct People s2 ={"小明",15,100};// 第二种方法struct People s3;//第三种方法
s3.age=18;
s3.phone=123456;
cout<<s1.name<<" 年龄:"<<s1.age<<"电话:"<<s1.phone<<endl;
cout<<s2.name<<" 年龄:"<<s2.age<<"电话:"<<s2.phone<<endl;
cout<<s3.name<<" 年龄:"<<s3.age<<"电话:"<<s3.phone<<endl;system("pause");}
2.2 结构体数组
将在定义的数组放入结构体中。
#include<iostream>#include<string>usingnamespace std;struct People
{//string name;//一些编译器设置string name;在初始化时会崩溃char name[20];int age;int phone;};intmain(){struct People arr[3]{{"小明",1,2},{"小红",10,20},{"小李",100,200},};system("pause");}
2.3 结构体指针
通过指针访问结构体的成员。
People s={"小明",1,2};
People *p=&s;
cout<<p->name<<p->age<<p->phone<<endl;system("pause");
2.4 结构体嵌套结构体
结构体中的成员可以是其他的结构体。
2.5 结构体作为函数参数
结构体作为参数向函数中传递。
两种方式:值传递和地址传递。
2.6 结构中const使用场景
防止错误操作,地址传递只占四个字节,将函数的形参改为指针可以减少占用空间,但会改变实参的值。
#include<iostream>#include<string>usingnamespace std;struct People
{char name[20];int age;int phone;};voidprint(const People *p){//p->age=100;//错误操作
cout<<p->name<<p->age<<p->phone<<endl;}intmain(){
People s={"小明",1,2};
People * p=&s;print(p);system("pause");}