大家来分析讨论函数调用的问题
先定义一个简单的结构:
typedef struct stu
{
char name[10];
int ID;
int score;
}stu;
函数返回引用
stu &fun(stu &student)
{
stu stu1;
stu1 = student;
return stu1;
}
int main()
{
stu student1 = {"name", 10101, 100};
stu &student2 = fun(student1);
cout << "score: " << student2.score << endl;
cout << "ID: " << student2.ID << endl;
cout << "name: " << student2.name << endl;
system("pause");
return 1;
}
运行后如图, 为什么出错?:
stu &fun(stu &student)
{
stu stu1;
stu1 = student;
return stu1;
}
int main()
{
stu student1 = {"name", 10101, 100};
stu student2 = fun(student1);
cout << "score: " << student2.score << endl;
cout << "ID: " << student2.ID << endl;
cout << "name: " << student2.name << endl;
//delete &student2;
//&student2 = NULL;
system("pause");
return 1;
}
运行后如图, 为什么正确?: