
ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ "САНКТ-ПЕТЕРБУРГСКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ ТЕЛЕКОММУНИКАЦИЙ ИМ. ПРОФ. М. А. БОНЧ-БРУЕВИЧА"
Факультет инфокоммуникационных сетей и систем
Кафедра сетей связи и передачи данных
Лабораторная работа №4
«ВИРТУАЛЬНЫЕ ФУНКЦИИ»
по дисциплине «Объектно-ориентированное программирование»
Выполнили:
студент 2-го курса
дневного отделения
группы ИКПИ-92
Козлов Никита
Санкт-Петербург
2020
Постановка задачи
Дополнить систему, состоящую из трех классов “Класс №1”, “Класс №2” и “Класс №3”, которые были разработаны в лабораторной работе 3, новым классом “Класс №4”. Новый класс должен быть связан public наследованием с классом “Класс №3”. Класс “Класс №4” должен иметь одно поле, которое выбирается студентом самостоятельно. Для разрабатываемого класса написать конструкторы умолчания, с параметрами и конструктор копирования, деструктор, методы доступа и метод print(). Метод print() в классах “Класс №2”, “Класс №3” и “Класс №4” должен быть виртуальным. Написать тестовую программу для проверки работоспособности разработанных классов. Разработать глобальную функцию printAll(), имеющую два параметра: массив указателей типа “Класс №2”* и количество элементов в этом массиве int n.
В тестовой программе массив указателей должен быть инициализирован адресами объектов типа “Класс №2”, “Класс №3” и “Класс №4”.
Пример.
|
Класс №3 |
Свойства (Класс №3) |
Класс №4 |
Свойства (Класс №4) |
Пример |
СDog (Собака) |
String NameDogs (Имя собаки, например – Ушастик) |
CPug (Мопс) |
Int AgePugs (Возраст Мопса, например – 5) СDog obj |
Код программы
Файл CPlayer.h
#pragma once
#include <iostream>
using namespace std;
/// <summary>
/// Class gives brief description of player
/// </summary>
class CPlayerDescription
{
private:
// Player number
int num;
// Player comand
string comand;
protected:
public:
// Default CPlayerDescription constructor
CPlayerDescription() { num = 0; comand = "DEFAULT_COMAND"; };
/*
Constructor with given values
@param number - number of player
@param comand_name - the team player plays for
*/
CPlayerDescription(int number, string comand_name) { num = number; comand = comand_name; };
~CPlayerDescription() { num = 0; comand = ""; };
// Set player number
void setNumber(int number);
// Set player comand
void setComand(string comand_name);
/// <summary>
/// Gets number from private field,
/// use for function in:
/// <seealso cref="FootbalPlayer::getPlayerInfo"/>
/// </summary>
int getNumber();
/// <summary>
/// Gets comand name from private field,
/// use for function in:
/// <seealso cref="FootbalPlayer::getPlayerInfo"/>
/// </summary>
string getComand();
// Overload to compare CPlayerDescription objects
bool operator == (const CPlayerDescription& source);
// Overload to use std::cout
friend ostream& operator << (ostream& os, const CPlayerDescription& source)
{
os << source.num << ", " << source.comand;
return os;
}
// Overload to equate CPlayerDescription objects
CPlayerDescription operator = (const CPlayerDescription& source)
{
this->num = source.num;
this->comand = source.comand;
return *this;
}
};
/// <summary>
/// Basic footbal player class
/// </summary>
class FootbalPlayer
{
protected:
// Name of player
string fullname;
CPlayerDescription description;
/// <summary>
/// Sets name to footbal player
/// </summary>
void setPlayerName(string name);
/// <summary>
/// Sets number to footbal player
/// </summary>
void setPlayerNumber(int number);
/// <summary>
/// Sets comand name to footbal player
/// </summary>
void setPlayerComand(string comand_name);
public:
// Default FootbalPlayer constructor
FootbalPlayer() { setPlayerName("DEFAULT"); };
/*
FootbalPlayer constructor with given values
@param name - name of the player
@param number - player number
@param comand - the team player plays for
*/
FootbalPlayer(string name, int number, string comand) {
setPlayerName(name);
description.setNumber(number);
description.setComand(comand);
};
~FootbalPlayer() {};
/// <summary>
/// Print all player info
/// </summary>
virtual void getPlayerInfo();
// Return player number
int getPlayerNumber();
// Return player comand
string getPlayerComand();
// Overload of '==' operator to compare FootbalPlayer objects
bool operator == (const FootbalPlayer& source);
// Overload of '<<' operator to use std::cout
friend ostream& operator << (ostream& os,const FootbalPlayer& source)
{
os << "[ " << source.fullname << ", " << source.description << " ]";
return os;
}
// Overload of '=' operator to
FootbalPlayer operator = (const FootbalPlayer& source)
{
this->fullname = source.fullname;
this->description = source.description;
return *this;
}
};
Файл CPlayer.cpp
#include "CPlayer.h"
void FootbalPlayer::setPlayerName(string name)
{
this->fullname = name;
}
void FootbalPlayer::getPlayerInfo()
{
cout <<"[ "<< fullname << ", "<< description.getNumber()<<", "<< description.getComand()<< " ]"<< endl;
}
void FootbalPlayer::setPlayerNumber(int number)
{
description.setNumber(number);
}
void FootbalPlayer::setPlayerComand(string comand_name)
{
description.setComand(comand_name);
}
int FootbalPlayer::getPlayerNumber()
{
return description.getNumber();
}
string FootbalPlayer::getPlayerComand()
{
return description.getComand();
}
bool FootbalPlayer::operator==(const FootbalPlayer& source)
{
if (this->fullname == source.fullname & description == source.description)
return true;
else
return false;
}
void CPlayerDescription::setNumber(int number)
{
this->num = number;
}
void CPlayerDescription::setComand(string comand_name)
{
this->comand = comand_name;
}
int CPlayerDescription::getNumber()
{
return this->num;
}
string CPlayerDescription::getComand()
{
return this->comand;
}
bool CPlayerDescription::operator==(const CPlayerDescription& source)
{
if (this->num == source.num & this->comand == source.comand)
return true;
else
return false;
}
Файл CGoalkeeper.h
#pragma once
#include "CPlayer.h"
// enum of goals side
typedef enum
{
LEFT = 0,
RIGHT = 1
}GOALS;
// FootbalPlayer with goalkeeper role
class CGoalkeeper : public FootbalPlayer
{
protected:
GOALS goalPos;
/// <summary>
/// Sets goals side to player
/// </summary>
/// <param name="GoalPosition">LEFT or RIGHT</param>
void setGoalPosition(const GOALS GoalPosition);
public:
/// <summary>
/// Default CGoalkeeper constructor
/// </summary>
CGoalkeeper() { goalPos = LEFT; };
~CGoalkeeper() { };
/// <summary>
/// CGoalkeeper copy constructor
/// </summary>
/// <param name="GoalPlayer">- CGoalkeeper object copy</param>
/// <returns></returns>
CGoalkeeper(const CGoalkeeper& GoalPlayer) {
fullname = GoalPlayer.fullname;
description = GoalPlayer.description;
goalPos = GoalPlayer.goalPos;
};
/// <summary>
/// CGoalkeepers constructor with a given values
/// </summary>
/// <param name="name">- goalkeeper name</param>
/// <param name="number">- goalkeeper number</param>
/// <param name="comand">- the team goalkeeper plays for</param>
/// <param name="GoalPosition">- goals side</param>
CGoalkeeper( string name, int number, string comand, const GOALS GoalPosition ) {
setPlayerName(name);
setPlayerNumber(number);
setPlayerComand(comand);
setGoalPosition(GoalPosition);
};
// Prints goalkeeper information
virtual void getPlayerInfo();
// Returns goal side
string getGoalPosition();
};
Файл CGoalkeeper.cpp
#include "CGoalkeeper.h"
void CGoalkeeper::setGoalPosition(const GOALS pos)
{
this->goalPos = pos;
}
string CGoalkeeper::getGoalPosition()
{
switch (goalPos) {
case LEFT:
return "left goals";
break;
case RIGHT:
return "right goals";
break;
}
return "";
}
void CGoalkeeper::getPlayerInfo()
{
cout << "[ " << fullname << ", " << description.getNumber() << ", "
<< description.getComand() << ", " << getGoalPosition() << " ]" << endl;
}
Файл CWinger.h
#pragma once
#include "CGoalkeeper.h"
// Winger type of footbal player class
class CWinger : public CGoalkeeper
{
private:
// Player speed
double spd;
protected:
/// <summary>
/// Sets winger speed
/// </summary>
/// <param name="speed">Speed in km/h</param>
void setWingerSpeed(double speed);
public:
// Default CWinger constructor
CWinger() { spd = 0; };
// CWinger copy constructor
CWinger(const CWinger& copyWinger) {
this->fullname = copyWinger.fullname;
this->description = copyWinger.description;
this->goalPos = copyWinger.goalPos;
this->spd = copyWinger.spd;
};
/// <summary>
/// CWinger constructor with a given values
/// </summary>
/// <param name="name">- Player name</param>
/// <param name="number">- Player number</param>
/// <param name="comand">- The team winger plays for</param>
/// <param name="goalPosition">- The wingers goal position</param>
/// <param name="speed">- Winger speed in km/h</param>
CWinger(string name, int number, string comand, const GOALS goalPosition, double speed) {
setPlayerName(name);
setPlayerNumber(number);
setPlayerComand(comand);
setGoalPosition(goalPosition);
setWingerSpeed(speed);
};
// CWinger destructor
~CWinger() { };
// Returns winger speed
double getWingerSpeed();
// Prints all winger information
virtual void getPlayerInfo();
};
Файл CWinger.cpp
#include "CWinger.h"
#include <assert.h>
void CWinger::setWingerSpeed(double speed)
{
assert(speed >= 1 && speed <= 20);
this->spd = speed;
}
double CWinger::getWingerSpeed()
{
return this->spd;
}
void CWinger::getPlayerInfo()
{
cout << "[ " << fullname << ", " << description.getNumber() << ", "
<< description.getComand() << ", " << getGoalPosition() << ", " << getWingerSpeed() <<"km/h"<< " ]" << endl;
}
Файл main.cpp
#include "CPlayer.h"
#include "CGoalkeeper.h"
#include "CWinger.h"
void PrintAll(FootbalPlayer ** ar, size_t n)
{
for (size_t i(0); i < n; i++)
{
ar[i]->getPlayerInfo();
cout << "----" << endl;
delete(ar[i]);
}
delete [] ar;
}
void main()
{
FootbalPlayer a("Friedrich Nietzsche", 16, "OverMan");
FootbalPlayer b("Friedrich Nietzsche", 16, "OverMan");
FootbalPlayer c("Karl Marx'", 3, "DasKapital");
a.getPlayerInfo();
b.getPlayerInfo();
c.getPlayerInfo();
if (a == b)
cout << "Equal" << endl;
else
cout << "Not equal" << endl;
if (a == c)
cout << "Equal" << endl;
else
cout << "Not equal" << endl;
CGoalkeeper ak("Karl Marx'", 3, "DasKapital", LEFT);
ak.getPlayerInfo();
CWinger pa("Nik Churchill", 28, "Zenit", RIGHT, 15);
pa.getPlayerInfo();
size_t n;
cout << "Enter players amount" << endl;
cin >> n;
FootbalPlayer** ar = new FootbalPlayer * [n];
ar[0] = new FootbalPlayer();
ar[1] = new CGoalkeeper();
ar[2] = new CWinger();
PrintAll(ar,n);
}
Работа программы