//在调用函数需要把结构体变量作为传递参数时,一般采用地址传递的方式,即构建一个结构体指针,
//这样做的好处是:传递参数所用的结构体指针在32位系统中只占4字节的存储空间,而使用值传递需要额外拷贝副本
//(为形参开辟存储空间),所以当传递参数众多时,使用地址传递可以大大节省存储空间;
//但使用地址传参的过程中可能会由于误操作而改变原有数据,所以可以通过使用常量指针的方式,在子函数的参数
//声明中使用形如(const struct Student *p)来使原有数据变为“只读”,以防止误修改;
//当在结构体定义中嵌套使用另一个结构体定义变量时,内部嵌套的结构体需要先定义,否则报错;
#include<iostream>
#include<cstring>
using namespace std;
struct Student
{
string no;
string name;
int score;
};
int print_stu(const Student *s)
{
// s -> score = 150; //加入const后该语句便会报错;
cout << "学生学号:" << s -> no << endl;
cout << "学生姓名:" << s -> name << endl;
cout << "学生成绩:" << s -> score << endl;
}
int main()
{
Student k;
Student *p = &k;//也可以写成const Student *p,但是此时对应子函数中的地址参数不能为
//Student *p,而必须写成const Student *p,因为“只读”必须传递给“只读”;
//但是“只读”对“可编辑”或“只读”均可接收;
cout << "请输入姓名:" << endl;
cin >> k.name;
cout << "请输入学号:" << endl;
cin >> k.no;
cout << "请输入成绩:" << endl;
cin>>k.score;
print_stu(p);
system("pause");
return 0;
}
#include<iostream>
#include<cstring>
using namespace std;
struct Student
{
string no;
string name;
int score;
}lisi = {"20150460110", "lisi", 100};//可以在结构体定义时创建结构体变量并整体赋初值;
//定义结构体时,struct不能省略,但创建一个结构体变量时struct可以省略;
//结构体变量利用 . 来访问成员;
int main()
{
Student syh;
syh.name = "sunyuhao";
syh.no = "20150460224";
syh.score = 150;
Student wangwu = {"20150460320", "wangwu", 120};//可以在创建结构体变量时整体赋初值;
//Student zhangsan = {"zhangsan", "20150460250", "60"}; 错误!不能单独为一个结构体变量整体赋初值;
cout << "姓名:" << syh.name << " 学号:" << syh.no << " 分数:" << syh.score << endl;
cout << "姓名:" << lisi.name << " 学号:" << lisi.no << " 分数:" << lisi.score << endl;
cout << "姓名:" << wangwu.name << " 学号:" << wangwu.no << " 分数:" << wangwu.score << endl;
system("pause");
return 0;
}