结构体及应用

定义

struct 结构体名 {结构成员列表};

创建方式

struct 结构体名 变量名

struct 结构体名 变量名 = {成员1,成员2}

代码

struct Strudent{
    string name;
    //成员名称
    int age;
    //成员年龄
    int score;
    //成员分数
}s3;//第三种创建结构体变量方法
//创建结构体变量

//第一种
struct Student s1;
s1.name = "张三";//定义属性
s1.age = 18;
s1.score = 95;

//第二种
struct Student s2 = {"李四",20,96}; 

结构体数组

struct Student stuArray[3] = 
    {
        {"张三",20,94}
        {"李四",18,97}
        {"王五",19,99}
    };

结构体指针

通过结构体指针,访问结构体数据中的属性使用“->”符号

//创建结构体
struct student{
    int age;
    string name;
    int score;
};
//新建指针
student s1 = {18,"小李",100};
student *p = &s1;
//输出
cout<<"名字:"<<*p->name<endl;

结构体嵌套结构体

#include<iostream>
#include<string>
using namespace std;

struct Student {
    string name;
    int age;
    int score;
};
struct Teacher{
    string name;
    int age;
    int ID;
    struct Student s;
};

void main(){
    //定义学生信息
    struct Student s;
    s1.age = 18;
    //定义老师信息
    Teacher t = {"李可",30,2010,s}
    cout<<t.s.age<<endl;
}

结构体做函数参数传递

#include<iostream>
#include<string>
using namespace std;

struct Teahcer {
    string name;
    int ID;
    int age;
}

void printTeacher1(struct Teacher t1){
    cout<<"子函数1中老师的名字为:"<<t1.name<<endl;
}

void printTeacher2(struct Teacher *p){
    cout<<"子函数2中老师的ID:"<<p->ID<<endl;

int main(){
    struct Teacher t1 = {"李可",17,30};
    struct Teacher t2 = {"李明",18,45}
    printTeacher(t1);//值传递
    printTeahcer(&t2);//指针传递
}

注:使用值传递时,在printTeacher1中修改结构体中的值不会对原本的值产生改变,而在printTeacher2中惊醒对数值的修改会直接修改本来结构体中的值。

结构体中const 的使用

#include<iostream>
#include<string>
using namespace std;

struct Student {
    string name;
    int age;
    int score;
};

void printStudent(const struct Student *p){//struct有与没有都一样
    //p->age = 25;会产生报错,const限制对结构体的修改
    cout<<结构体1中学生的年龄为:<<p->age<<endl;
}

int main(){
    struct Student s1 = {"李可",30,95};
    printStudent(&s1);
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值