1 #include<iostream> 2 #include<fstream> 3 #include<string.h> 4 using namespace std; 5 6 class Student; 7 8 typedef void(CALL)(Student*,int); 9 10 class Student 11 { 12 public: 13 string name; 14 int age; 15 char sex; 16 public: 17 Student(){} 18 ~Student(){} 19 }; 20 21 void write_object(Student *students,int size) 22 { 23 ofstream ofs("text.bat"); 24 if(ofs) 25 { 26 for(int i=0;i<size;i++) 27 { 28 cin>>students[i].name>>students[i].age>>students[i].sex; 29 ofs.write(reinterpret_cast<const char*>(&students[i]),sizeof(students[i])); 30 } 31 } 32 else 33 { 34 cout<<"write failed"<<endl; 35 } 36 ofs.close(); 37 } 38 39 void read_object(Student *students,int size) 40 { 41 ifstream ifs("text.bat"); 42 if(ifs) 43 { 44 for(int i=0;i<size;i++) 45 { 46 ifs.read(reinterpret_cast<char*>(&students[i]),sizeof(students[i])); 47 } 48 } 49 else 50 { 51 cout<<"write failed"<<endl; 52 } 53 ifs.close(); 54 } 55 56 void show_students(Student *students,int size) 57 { 58 for(int i=0;i<size;i++) 59 { 60 cout<<students[i].name<<","<<students[i].age<<","<<students[i].sex<<endl; 61 } 62 } 63 64 #if 0 65 void clear(Student *students,int size) 66 { 67 for(int i=0;i<size;i++) 68 { 69 memset(reinterpret_cast<void*>(&students[i]),0,sizeof(students[i])); 70 } 71 } 72 #endif 73 74 int main() 75 { 76 Student students[3]; 77 int size = sizeof(students)/sizeof(students[0]); 78 79 CALL *arrays[5]={write_object,show_students,read_object,show_students,clear}; 80 81 for(int i=0;i<5;i++) 82 { 83 arrays[i](students,size); 84 } 85 86 return 0; 87 }
函数指针数组的最佳实践
猜你喜欢
转载自www.cnblogs.com/running-world/p/11355519.html
今日推荐
周排行