`
dixian
  • 浏览: 15197 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

File IO

阅读更多

头文件:

#ifndef STUDENT_H_
#define STUDENT_H_

#include <string>

using namespace std;

class Student {
public:
	Student();
	Student(string, char, string, int);

	void setFirstName(string);
	void setMiddleName(char);
	void setLastName(string);
	void setScore(int);

	string getFirstName();
	char getMiddleName();
	string getLastName();
	int getScore();

private:
	string firstName;
	char middleName;
	string lastName;
	int score;
};

Student::Student() {
}
Student::Student(string firstName, char middleName, string lastName, int score) {
	setFirstName(firstName);
	setMiddleName(middleName);
	setLastName(lastName);
	setScore(score);
}

void Student::setFirstName(string firstName) {
	this->firstName = firstName;
}
void Student::setMiddleName(char middleName) {
	this->middleName = middleName;
}
void Student::setLastName(string lastName) {
	this->lastName = lastName;
}
void Student::setScore(int score) {
	this->score = score;
}

string Student::getFirstName() {
	return firstName;
}
char Student::getMiddleName() {
	return middleName;
}
string Student::getLastName() {
	return lastName;
}
int Student::getScore() {
	return score;
}
#endif /* STUDENT_H_ */
 

测试类:

#include <iostream>
#include <fstream>

#include "Student.h"

using namespace std;

void displayStudent(Student stu);

int main() {
	Student stu1("John", 'T', "Smith", 90);
	Student stu2("Eric", 'K', "Jones", 80);
	displayStudent(stu1);
	displayStudent(stu2);

	fstream binaryio;
	binaryio.open("stu.dat", ios::out | ios::binary);
	binaryio.write(reinterpret_cast<char*> (&stu1), sizeof(stu1));
	binaryio.write(reinterpret_cast<char*> (&stu2), sizeof(stu2));
	binaryio.close();

	cout << "--------------------" << endl;

	Student stu;
	binaryio.open("stu.dat", ios::in | ios::binary);

	binaryio.read(reinterpret_cast<char*> (&stu), sizeof(stu));
	displayStudent(stu);
	binaryio.read(reinterpret_cast<char*> (&stu), sizeof(stu));
	displayStudent(stu);
	binaryio.close();
}

void displayStudent(Student stu) {
	cout << stu.getFirstName() << " " << stu.getMiddleName() << " " << stu.getLastName() << " " << stu.getScore() << endl;
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics