C++结构体

结构体定义和使用

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

通过结构体创建变量的方式有三种:

  • struct 结构体名 变量名
  • struct 结构体名 变量名 = { 成员1值 , 成员2值…}
  • 定义结构体时顺便创建变量
#include <iostream>
#include <string>
using namespace std;
struct student
{
    string name;
    int age;
}stu3;
// 方式3:定义了一个结构体变量名为stu3
int main(int argc,char* argv[])
{
    // 方式1:定义结构体变量
    student stu1;
    stu1.name = "liming";
    stu1.age = 24;
    cout<<stu1.name<<"   "<<stu1.age<<endl;

    // 方式2:定义了结构体变量
    student stu2 = {"wanglei",24};
    cout<<stu2.name<<"   "<<stu2.age<<endl;
}

结构体指针

作用:通过指针访问结构体中的成员

  • 利用操作符 ->可以通过结构体指针访问结构体属性
#include <iostream>
#include <string>
using namespace std;
struct student
{
    string name;
    int age;
};
int main(int argc,char* argv[])
{
    student stu1;
    student* ptr_stu1 = &stu1;
    ptr_stu1->name = "liming";
    ptr_stu1->age = 24;
    cout<<ptr_stu1->name<<"   "<<ptr_stu1->age<<endl;
}

结构体嵌套结构体

#include <iostream>
#include <string>
using namespace std;
struct student
{
    string name;
    int age;
    int score;
};
struct teacher
{
    string name;
    int age;
    student stu;
};
int main(int argc,char* argv[])
{
    teacher t1;
    t1.name = "wanghong";
    t1.age = 45;
    t1.stu.name = "liming";
    t1.stu.age = 24;
    t1.stu.score = 100;
    cout<<"the score of "<<t1.stu.name<<" is "<<t1.stu.score<<endl;
}

结构体作函数参数

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

传递方式有两种:

  • 值传递
  • 地址传递
#include <iostream>
#include <string>
using namespace std;
struct student
{
    string name;
    int age;
    int score;
};
void value_transmit(student stu1)
{
    stu1.score = 60;
    cout<<"the score of "<<stu1.name<<" is "<<stu1.score<<endl;
    return;
}
void add_transmit(student* stu1)
{
    stu1->score = 60;
    cout<<"the score of "<<stu1->name<<" is "<<stu1->score<<endl;
    return;
}
int main(int argc,char* argv[])
{
    student stu1;
    stu1.name = "liming";
    stu1.score = 100;
    stu1.age = 20;
    cout<<"the score of "<<stu1.name<<" is "<<stu1.score<<endl;
    value_transmit(stu1);
    cout<<"the score of "<<stu1.name<<" is "<<stu1.score<<endl;
    add_transmit(&stu1);
    cout<<"the score of "<<stu1.name<<" is "<<stu1.score<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值