19.12.2012, 15:19
общий
это ответ
Здравствуйте, Сергей!
Вот код, чуть позже более подробные комментарии добавлю, сейчас не успеваю.
Приложение:
#pragma once
#ifndef EDITIONS_H
#define EDITIONS_H
#include <string>
#include <vector>
#include <map>
using namespace std;
/*Описатель учебного издания содержит: фамилию и инициалы автора, название издания, год и издательство,
количество экземпляров, название курса использующего это издание и перечень индексов групп(1-8).
Описатель научного издания содержит: фамилию и инициалы автора, название издания, год и издательство,
количество экземпляров, названия курсов использующего это издание(1-3).
Описатель художественного издания содержит: фамилию и инициалы автора, название издания, год и издательство,
количество экземпляров, тематика литературного произведения.
Каждое издание содержит уникальную хар-ку – шифр издания. Информация обо всех изданиях, хранящихся в библиотеке,
сведена в таблицу, каждый элемент которой содержит шифр издания и указатель на его описатель. Элементы таблицы
упорядочены по возрастанию значений шифра.
*/
enum EditionType { //типы изданий
Academic = 0, //учебное
Scientific = 1, //научное
Fiction = 2 //худож
};
class IEdition //ихдание
/*Для любого издания:
1) Вывести информацию об издании
2) Вернуть в качестве результата тип литературы
3) Вернуть количество экземпляров , изменить количество экземпляров
*/
{
protected:
int code; //шифр
EditionType type; //тип
string author; //автор
string name; //название
string publisher; //издательство
int year; //год
int count; //количество
public:
IEdition () : code(0),type(Academic){}; //констуктор по умолчанию
IEdition (int code_, EditionType type_, string author_, string name_, string pub, int year_, int count_) :
code (code_), type (type_), author (author_), name (name_), publisher (pub), year (year_), count (count_) {};
void Print (); //печать
string GetEditionType (); //тип в строковом виде
int GetType (); //тип в числовом виде
int GetCount (); //количество
void SetCount (int newcount); //изменить кол-во
int GetCode (); //получить шифр
virtual void Save (FILE* file); //сохранить
virtual void Load (FILE* file); //загрузить
};
/*Для учебного или научного издания:
1) Вернуть в качестве результата перечень названий курсов, использующих это издание
2) Изменить или добавить название курса, использующего это издание
*/
class AcademicEdition : public IEdition
{
string className; //курс
vector <string> index; //индексы
public:
AcademicEdition () : IEdition() {};
string GetClassName (); //получить курс
void SetClassName (string newclass); //установить курс
private:
virtual void Save (FILE* file); //сохранить
virtual void Load (FILE* file); //загрузить
};
class ScientificEdition : public IEdition
{
vector <string> classes; //курсы
public:
ScientificEdition () : IEdition() {};
vector<string>& GetClasses (); //курсы
void AddClass (string newclass); //добавить курс
void ChangeClass (string oldclass, string newclass); //изменить курс
void RemoveClass (string classname); //удалить курс
private:
virtual void Save (FILE* file);
virtual void Load (FILE* file);
};
class FictionEdition : public IEdition
{
string theme; //тема
public:
FictionEdition () : IEdition() {};
string GetTheme (); //получить
private:
virtual void Save (FILE* file);
virtual void Load (FILE* file);
};
class Library
/*Для таблицы:
1) Включить новый элемент, не нарушаю упорядочнности
2) Найти элемент по шифру
3) Удалить элемент по шифру
4) Показать содержимое таблицы
*/
{
map <int, IEdition*> editions; //таблица изланий
public:
~Library ();
void AddNewEdition (IEdition* newedition); //добавить новое
IEdition* FindEdition (int code); //найти
void RemoveEdition (int code); //удалить
void PrintLibrary (); //напечатать всю инфу
void SaveToFile (string filename); //сохранить в файл
void LoadFromFile (string filename);
};
#endif
#include "StdAfx.h"
#include "Editions.h"
#include <iostream>
#include <algorithm>
using namespace std;
string EditionNames [] = {"Учебное издание", "Научное издание", "Художественное издание"}; //тестовые типы
void IEdition::Print ()
{
cout << endl << code << ": " << EditionNames[(int)type] << ", " << name << ". "
<< author << ", " << publisher << ":" << year << " - " << count << "шт";
}
string IEdition::GetEditionType ()
{
return EditionNames[(int)type]; //выбор текстового типа
}
int IEdition::GetType ()
{
return type;
}
int IEdition::GetCount ()
{
return count;
}
void IEdition::SetCount (int newcount)
{
count = newcount;
}
int IEdition::GetCode ()
{
return code;
}
void IEdition::Save (FILE* file)
{ //сохраняем в бинарный файл общую инфу об издании
fwrite (&code, sizeof(int), 1, file);
fwrite (&type, sizeof(EditionType), 1, file);
int l = name.size()+1;
fwrite (&l, sizeof(int), 1, file);
fwrite (name.c_str(), sizeof(char), l, file);
l = author.size()+1;
fwrite (&l, sizeof(int), 1, file);
fwrite (author.c_str(), sizeof(char), l, file);
l = publisher.size()+1;
fwrite (&l, sizeof(int), 1, file);
fwrite (publisher.c_str(), sizeof(char), l, file);
fwrite (&year, sizeof(int), 1, file);
fwrite (&count, sizeof(int), 1, file);
}
void IEdition::Load (FILE* file)
{//грузим общую инфу
fread (&code, sizeof(int), 1, file);
fread (&type, sizeof(EditionType), 1, file);
int l = name.size();
fread (&l, sizeof(int), 1, file);
char buf [256];
fread (buf, sizeof(char), l, file);
name = buf;
fread (&l, sizeof(int), 1, file);
fread (buf, sizeof(char), l, file);
author = buf;
fread (&l, sizeof(int), 1, file);
fread (buf, sizeof(char), l, file);
publisher = buf;
fread (&year, sizeof(int), 1, file);
fread (&count, sizeof(int), 1, file);
}
//------------------------------------------------------------//
string AcademicEdition::GetClassName ()
{
return className;
}
void AcademicEdition::SetClassName (string newclass)
{
className = newclass;
}
void AcademicEdition::Save (FILE* file)
{
IEdition::Save (file); //сохраняем общую инфу
//сохраняем специфическую для данного типа инфу
int l = className.size()+1;
fwrite (&l, sizeof(int), 1, file);
fwrite (className.c_str(), sizeof(char), l, file);
l = index.size();
fwrite (&l, sizeof(int), 1, file);
for (int i=0; i<index.size(); i++) {
l = index[i].size()+1;
fwrite (&l, sizeof(int), 1, file);
fwrite (index[i].c_str(), sizeof(char), l, file);
}
}
void AcademicEdition::Load (FILE* file)
{//то же по загрузке
IEdition::Load (file);
int l;
char buf [256];
fread (&l, sizeof(int), 1, file);
fread (buf, sizeof(char), l, file);
className = buf;
fread (&l, sizeof(int), 1, file);
for (int i=0; i<l; i++) {
fread (&l, sizeof(int), 1, file);
fread (buf, sizeof(char), l, file);
index.push_back (buf);
}
}
//------------------------------------------------------------//
vector<string>& ScientificEdition::GetClasses ()
{
return classes;
}
void ScientificEdition::AddClass (string newclass)
{
classes.push_back (newclass);
}
void ScientificEdition::ChangeClass (string oldclass, string newclass)
{
for (int i=0; i<classes.size(); i++)
if (classes[i] == oldclass) { classes[i] = newclass; break;}
}
void ScientificEdition::RemoveClass (string classname)
{
for (vector<string>::const_iterator i = classes.begin(); i!=classes.end(); i++)
if (*i == classname) { classes.erase (i); return; }
}
void ScientificEdition::Save (FILE* file)
{
IEdition::Save (file);
int l = classes.size();
fwrite (&l, sizeof(int), 1, file);
for (int i=0; i<classes.size(); i++) {
l = classes[i].size()+1;
fwrite (&l, sizeof(int), 1, file);
fwrite (classes[i].c_str(), sizeof(char), l, file);
}
}
void ScientificEdition::Load (FILE* file)
{
IEdition::Load (file);
int l;
char buf[256];
fread (&l, sizeof(int), 1, file);
for (int i=0; i<l; i++) {
fread (&l, sizeof(int), 1, file);
fread (buf, sizeof(char), l, file);
classes.push_back (buf);
}
}
//------------------------------------------------------------//
string FictionEdition::GetTheme ()
{
return theme;
}
void FictionEdition::Save (FILE* file)
{
IEdition::Save (file);
int l = theme.size()+1;
fwrite (&l, sizeof(int), 1, file);
fwrite (theme.c_str(), sizeof(char), l, file);
}
void FictionEdition::Load (FILE* file)
{
IEdition::Load (file);
int l;
char buf [256];
fread (&l, sizeof(int), 1, file);
fread (buf, sizeof(char), l, file);
theme = buf;
}
//------------------------------------------------------------//
void Library::AddNewEdition (IEdition* newedition)
{
editions[newedition->GetCode()] = newedition;
}
IEdition* Library::FindEdition (int code)
{
if (editions.find (code) != editions.end())
return editions[code];
else return NULL;
}
void Library::RemoveEdition (int code)
{
editions.erase (code);
}
void Library::PrintLibrary ()
{
for (map<int, IEdition*>::const_iterator i = editions.begin(); i!=editions.end(); i++)
i->second->Print ();
}
void Library::SaveToFile (string filename)
{
FILE* file = fopen (filename.c_str(), "wb");
int l = editions.size();
fwrite (&l, sizeof(int), 1, file);
for (map<int, IEdition*>::const_iterator i = editions.begin(); i!=editions.end(); i++) {
l = i->second->GetType();
fwrite (&l, sizeof(int), 1, file);
i->second->Save (file);
}
fclose (file);
}
void Library::LoadFromFile (string filename)
{
FILE* file = fopen (filename.c_str(), "rb");
int l;
fread (&l, sizeof(int), 1, file);
for (int i=0; i<l; i++) {
fread (&l, sizeof(int), 1, file);
IEdition* ne;
switch ((EditionType)l) {
case Academic:
ne = new AcademicEdition;
break;
case Scientific:
ne = new ScientificEdition;
break;
case Fiction:
ne = new FictionEdition;
break;
}
ne->Load (file);
editions[ne->GetCode()] = ne;
}
fclose (file);
}
Library::~Library ()
{
for (map<int, IEdition*>::const_iterator i = editions.begin(); i!=editions.end(); i++)
delete i->second;
}