Skip to content

Latest commit

 

History

History
57 lines (44 loc) · 956 Bytes

211105.md

File metadata and controls

57 lines (44 loc) · 956 Bytes

结构体与函数

结构体如何在函数中当作参数传递

值传递

在函数内部修改不改变原来的值

#include<iostream>
#include<string>

using namespace std;

struct Teacher {
    string name;
    int age;
};

void showTeacherFn (Teacher t) {
    t.age = 30;
    cout << t.name << "的年龄为:" << t.age << endl;
}

int main () {
    Teacher t = {"张三", 25};
    showTeacherFn(t);
    cout << t.age << endl;
    return 0;
}

地址或者说指针传递

在函数内部修改会改变原来的值

#include<iostream>
#include<string>

using namespace std;

struct Teacher {
    string name;
    int age;
};

void showTeacherPointFn (Teacher *t) {
    t->age = 30;
    cout << t->name << "的年龄为:" << t->age << endl;
}

int main () {
    Teacher t = {"张三", 25};
    showTeacherPointFn(&t);
    cout << t.age << endl;
    return 0;
}