为什么程序在打印完成之后崩了

#include<iostream>
#include<string>
#include<vector>
#include<fstream>
using namespace std;
enum ESex {
	male,
	female
};

enum EClass {
	class1=1,
	class2,
	class3,
	class4,
	class5,
};

class Student {
public:
	ESex Sex;
	EClass Class;
	string Name;
	Student() {}
	Student(ESex s,EClass c,string n) {
		Sex = s;
		Class = c;
		Name = n;
	}
};

void print_stu(Stu s) {
	if (s.Sex == male) cout << "男";
	else cout << "女";
	cout << "\t";

	cout << s.Class << "\t";

	cout << s.Name << endl;
	
}
void test45()
{
	ofstream ofs;
	Student a(male, class1, "张三");
	Student b(female, class5, "李四");
	Student c(male, class2, "王五");

	ofs.open("test01.txt", ios::out);

	ofs.write((const char*)&a, sizeof(Student));
	ofs.write((const char*)&b, sizeof(Student));
	ofs.write((const char*)&c, sizeof(Student));

	ofs.close();

}
void test_45()
{
	ifstream ifs;
	Student a;
	Student b;
	Student c;

	ifs.open("test01.txt", ios::in);

	ifs.read((char*)&a, sizeof(Student));
	ifs.read((char*)&b, sizeof(Student));
	ifs.read((char*)&c, sizeof(Student));

	ifs.close();
	cout << "性别\t" << "班级\t" << "姓名" << endl;
	print_stu(a);
	print_stu(b);
	print_stu(c);

}

int main() {

	test45();
    test_45();

	system("pause");
	return 0;

}

 

1.崩溃原因:

test_45()函数中的a、b、c对象试图指向函数test45()里a、b、c对象,但是test45()函数会在函数执行结束后析构调a、b、c对象的,test_45()去访问已经析构对象的内存造成崩溃。

可以在test45()里a、b、c对象加上static修饰,不过不推荐把对象的内存地址保存到文件之后再取对象的地址访问

 

2.这个代码应该编译不过吧?

void print_stu(Stu s) 应该修改为:

void print_stu(Student s)

 

 

void print_stu(Stu s) { 这一行改成 void print_stu(Student s) {