结构体可以作为形参进行传递数据,其中传递的方式有 “值传递” 与 “地址传递”。但这两种传递方式区别截然不同。

值传递:

相当于传一份拷贝的数据。
例如下面我要将张三的姓名进行重新赋值。但是不会影响原来的值,

#include <iostream>
#include <string.h>
using namespace std;
struct Student{
    string name;
    int age;
    int score;
};
void printStudent(Student student){
    //并没有修改数据源,只是修改了拷贝的数据
    student.name = "陈陈菌";
    cout << "姓名:" <<student.name << endl;
    cout << "年龄:" <<student.age << endl;
    cout << "成绩:" <<student.score << endl;
}
int main(){
    Student student;
    Student * studentp;
    studentp = &student;
    student.name ="张三";
    student.age = 20;
    student.score = 99;

    cout << "子函数打印:" << endl;
    printStudent(student);

    cout << "\n主函数打印:" << endl;
    cout << "姓名:" <<student.name << endl;
    cout << "年龄:" <<student.age << endl;
    cout << "成绩:" <<student.score << endl;
    return 0;
}

结构体传递.png
运行结果:

子函数打印:
姓名:陈陈菌
年龄:20
成绩:99

主函数打印:
姓名:张三
年龄:20
成绩:99

地址传递:

相当于传数据源。
只有这样才会修改数据源。

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

struct Student{
    string name;
    int age;
    int score;
};
void printStudent(Student * student){
    student->name = "陈陈菌";
    cout << "姓名:" <<student->name << endl;
    cout << "年龄:" <<student->age << endl;
    cout << "成绩:" <<student->score << endl;
}
int main(){
    Student student;
    Student * studentp;
    studentp = &student;
    student.name ="张三";
    student.age = 20;
    student.score = 99;

    cout << "子函数打印:" << endl;
    printStudent(studentp);

    cout << "\n主函数打印:" << endl;
    cout << "姓名:" <<student.name << endl;
    cout << "年龄:" <<student.age << endl;
    cout << "成绩:" <<student.score << endl;
    return 0;
}

结构体传递2.png

运行结果:

子函数打印:
姓名:陈陈菌
年龄:20
成绩:99

主函数打印:
姓名:陈陈菌
年龄:20
成绩:99
文章目录