看如下代码:
#include<iostream>
using namespace std;#include<string>//结构体
struct Student {string name;int age;int score;}st3;//值传递
void printStufdents(struct Student st2) {cout << "子函数" << endl;st2.age = 150;cout << "名字:" << st2.name << " 年龄:" << st2.age << " 分数:" << st2.score << endl;
}//指针传递只占四个字节 节省内存空间 而且不会复制新的副本出来
void printStufdents(struct Student *s) {cout << "子函数" << endl;s->age = 150;cout << "名字:" << s->name << " 年龄:" << s->age << " 分数:" << s->score << endl;
}int main() {struct Student st2 = { "张三丰",120,70 };cout << "名字" << st2.name << "年龄" << st2.age << "分数" << st2.score<< endl;printStufdents(st2);system("pause");
}
1,地址传递只占四个字节 节省内存空间 而且不会复制新的副本出来
2,地址传递有个问题,会改变地址的值,为了防止误操作,我们引入了const关键字修饰指针
#include<iostream>
using namespace std;#include<string>//结构体
struct Student {string name;int age;int score;
}st3;void printStufdents(struct Student st2) {cout << "子函数" << endl;st2.age = 150;cout << "名字:" << st2.name << " 年龄:" << st2.age << " 分数:" << st2.score << endl;
}//指针传递只占四个字节 节省内存空间 而且不会复制新的副本出来
void printStufdents(const struct Student *s) {cout << "子函数" << endl;s->age = 150;cout << "名字:" << s->name << " 年龄:" << s->age << " 分数:" << s->score << endl;
}int main() {struct Student st2 = { "张三丰",120,70 };cout << "名字" << st2.name << "年龄" << st2.age << "分数" << st2.score<< endl;printStufdents(st2);system("pause");
}