#include <iostream>
#include <string>
using namespace std;
//定义学生结构体
struct Student {
//定义成员列表
string name;
int age;
int score;
};
//值传递
void printStudent1(struct Student s) {
s.age = 100;
cout << "子函数1中 姓名:" << s.name << "年龄:" << s.age << "分数:" << s.score << endl;
}
//地址传递
void printStudent2(const Student *p) {
//p->age = 200; //加入const后,一旦有修改的操作就会报错,可以防止误操作
cout << "子函数2中 姓名:" << p->name << "年龄:" << p->age << "分数:" << p->score << endl;
}
int main() {
struct Student s;
s.name = "张三";
s.age = 19;
s.score = 90;
printStudent1(s);
printStudent2(&s);
cout << "main函数中 姓名:" << s.name << "年龄:" << s.age << "分数:" << s.score << endl;
system("pause");
return 0;
}
- 值传递 是将值复制一份
- 地址传递不会复制而是直接用原数据,所有占用内存会少于值传递