Представление информации (данных о книге: фамилия автора, название и год издания) в виде класса

Страницы работы

6 страниц (Word-файл)

Содержание работы

Министерство образования и науки, молодежи и спорта

Национальный аэрокосмический университет им. Н.Е.Жуковского “ХАИ”

кафедра 304

Лабораторная работа №4

по предмету «Программирование»

Выполнил студент

315 группы

Гармашов А.В.

Проверил

доц. каф. 304

Бакуменко Н.С.

Харьков 2013

Лабораторная работа №4

«Классы»

Цель: Изучить теоретический и практический материал по теме.

Постановка задачи:

1.  Работа должна содержать, по крайней мере, два класса – первый, описывающий поля Вашего класса, согласно заданию, а второй – содержащий массив из элементов первого класса.

2.  Каждый из классов должен иметь, по крайней мере, один конструктор. Если класс содержит указатели, то и деструктор.

3.  Все поля каждого класса должны быть описаны как private

4.  Для каждого класса необходимо реализовать - переопределить операции ввода-вывода <<и>>, например, как дружественные функции.

5.  Методы класса, которые решаю т задачи Вашего варианта, не должны что-то выводить на печать, в файл, а также получать информацию непосредственно из файла (кроме операций <<и>>). Исходные данные – поля класса и параметры, результаты – поля класса, параметры и возвращение результата через return.

6.   Текст программы должен содержать, пусть минимальные, спецификации – комментарии.

7.  Для своего класса (классов) переопределить какую-нибудь операцию (операции). По возможности операции должны быть полезными при выполнении заданий Вашего варианта.

Вариант 3

Книга: фамилия автора, название и год издания.

Найти: название книг данного автора; самое старое издание.

Текст программы:

Файл “Class_Matrix.h”:

/* This file describes class "Matrix",

which is array of elements of the class

"Biblios". */

#include "stdafx.h"

#include <iostream>

#include <string>

#include "cstdlib" // library to clear the screen

#include <iomanip> // there is setw ()

#include <fstream> // file library

using namespace std;

class Matrix

{           

int n; // n - the amount of added books

Biblos* Massiv;

public:

       int nn() {return n;} // function returns integer value "n" which makes it possible to use in other functions and classes

       Biblos* mm() {return Massiv;} // function returns value "Massiv" which makes it possible to use in other functions and classes

Matrix(int=1); // constructor

~Matrix(); // destruclor

friend istream& operator>>(istream& ccin, Matrix &B); // override operation ">>"

friend ostream& operator<<(ostream& out, Matrix &B); // override operation "<<"

int operator!(); //searching for the oldes edition

};

int Matrix::operator!()

{

       int old = Massiv[0].yy();

       for (int i = 1; i<n; ++i)

             if (Massiv[i].yy()<old) old = Massiv[i].yy();

return old;

}

Matrix::Matrix(int a) : n(a)

{

       if (a>0)

       Massiv = new Biblos [a]; else cout<<"ERROR!"<<endl;

}

Matrix::~Matrix()

{

       if (n>0)

delete []Massiv;

}

istream& operator>>(istream& ccin, Matrix &B)

{

       cout<<"Enter the number of books you want to add to the database: ";

       ccin>>B.n;

       if (B.n>0)

       {

B.Massiv = new Biblos [B.n];

for (int i = 0; i<B.n; i++)

{

       ccin>>B.Massiv[i];

    system("cls");

}

       }

       return ccin;

}

ostream& operator<<(ostream& out, Matrix &B)

{

       out<<"Title of the Book:"<<setw(30);

       out<<"Autor of the Book:"<<setw(30);

       out<<"The Publishing Year:"<<endl;

       for (int i=0; i<B.n; i++)

       {

             int dif;

             dif = B.Massiv[i].tt().length()-B.Massiv[0].tt().length();

             out<<B.Massiv[i].tt()<<setw(30-dif);

           out<<B.Massiv[i].aa()<<setw(30);

             out<<B.Massiv[i].yy()<<endl;

       }

       out<<"The oldest edition: "<<!B;

       return out;

}

Файл “Class_Biblos.h”:

/* This file describes a class

that includes informations about the book:

Title, Autor, Publishing year. */

#include "stdafx.h"

#include <iostream>

#include <string>

using namespace std;

class Biblos

{

string Title; // the title of the book

string Autor; // the autor of the book

int Year; // the publishing year

public:

       int yy(){return Year;} // function returns integer value "Year" which makes it possible to use in other functions and classes

       string tt(){return Title;}

       string aa(){return Autor;}

Biblos(string="",string="",int=0); // constructor

friend istream& operator>>(istream& input, Biblos &B); // override operation ">>"

friend ostream& operator<<(ostream& out, Biblos &B); // override operation "<<"

};

Biblos::Biblos (string a,string b,int c) :

Title(a),

    Autor(b),

       Year(c) {}

istream& operator>>(istream& input, Biblos &B)

{

 cout<<"Input Title of the Book:"<<endl;

 input>>B.Title;

 cout<<"Input Autor of the book:"<<endl;

 input>>B.Autor;

 cout<<"Input the Publishing Year:"<<endl;

 input>>B.Year;

 return input;

}

ostream& operator<<(ostream& out, Biblos &B)

{

       out<<B.Title;

       out<<B.Autor;

    out<<B.Year<<endl;

       return out;

}

Основной файл “Lab №4.cpp”:

// Lab №4.cpp: определяет точку входа для консольного приложения.

//

#include "stdafx.h"

#include <iostream>

#include <string>

#include "cstdlib" // library to clear the screen

#include <iomanip> // there is setw ()

#include "Class_Biblos.h"

#include "Class_Matrix.h"

using namespace std;

int main()

{

       setlocale(LC_ALL,"RUSSIAN");

       Matrix M;

       cin>>M;

       system("cls");

       cout<<M<<endl;

       system("pause");

             return 0;

}

Результат:

Выводы:

·  Получены навыки работы с классами

·  Изучен теоретический и практический материал по теме

Похожие материалы

Информация о работе

Тип:
Отчеты по лабораторным работам
Размер файла:
60 Kb
Скачали:
0