结构体作为函数参数也是分为三种传递方式:
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进行解决。
注:本文章仅为学习路线中感悟,有错误之处还请指出!