C++之结构体作函数参数

结构体作为函数参数也是分为三种传递方式:

        1、值传递

        2、地址传递

        3、引用传递

依然遵从值传递形参改变不影响实参,地址传递形参改变影响实参,引用传递形参改变影响实参的原则。


不同之处为,三种传递方法传递时所操作方式不同。

1、值传递例(使用构造体成员时用"."操作):

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
struct Student{//声明学生构造体
    int age;
    string name;
};
struct Teacher//声明老师构造体
{
    int age;
    string name;
    Student student;
};
void IntroduceTeach(Teacher teacher){//老师构造体作为函数参数
    cout << "Name: " << teacher.name << endl;
    cout << "Age: " << teacher.age << endl;
    cout << "Student age: " << teacher.student.age<< endl;
    cout << "Student name: " << teacher.student.name << endl;
}
int main(int argc, char const *argv[])
{
   struct Teacher tea;
   struct Student stu;
   stu.age = 15;
   stu.name = "张三";
   tea.age = 35;
   tea.name = "李华";
   tea.student = stu;
   IntroduceTeach(tea);//函数调用
}

输出:


 2、地址传递例(使用构造体成员时用"->"操作):

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
struct Student{//声明学生构造体
    int age;
    string name;
};
struct Teacher//声明老师构造体
{
    int age;
    string name;
    Student student;
};
void IntroduceTeach(Teacher *teacher){//老师构造体作为函数参数
    cout << "Name: " << teacher->name << endl;
    cout << "Age: " << teacher->age << endl;
    cout << "Student age: " << teacher->student.age<< endl;
    cout << "Student name: " << teacher->student.name << endl;
}
int main(int argc, char const *argv[])
{
   struct Teacher tea;
   struct Student stu;
   stu.age = 15;
   stu.name = "张三";
   tea.age = 35;
   tea.name = "李华";
   tea.student = stu;
   IntroduceTeach(&tea);//函数调用
}

输出:


 2、引用传递例(使用构造体成员时用"."操作):

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
struct Student{//声明学生构造体
    int age;
    string name;
};
struct Teacher//声明老师构造体
{
    int age;
    string name;
    Student student;
};
void IntroduceTeach(Teacher &teacher){//老师构造体作为函数参数
    cout << "Name: " << teacher.name << endl;
    cout << "Age: " << teacher.age << endl;
    cout << "Student age: " << teacher.student.age<< endl;
    cout << "Student name: " << teacher.student.name << endl;
}
int main(int argc, char const *argv[])
{
   struct Teacher tea;
   struct Student stu;
   stu.age = 15;
   stu.name = "张三";
   tea.age = 35;
   tea.name = "李华";
   tea.student = stu;
   IntroduceTeach(tea);//函数调用
}

输出:


 推荐结构体作为参数时进行引用传递或地址传递:

        1、如果进行地址传递就不会令在内存中开辟大块空间去储存变量,只需要一个指针的内存大小即可,如果担心不小心改变了原本的值,则可以使用常量指针进行传递。

        2、而引用的本质也是指针,如果担心不小心改变了原本的值,也可以前面加const进行解决。

注:本文章仅为学习路线中感悟,有错误之处还请指出! 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农永闯天涯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值