Вы находитесь на странице: 1из 15

Министерство Образования, Культуры и Исследований

Технический Университет Молдовы


Факультет Вычислительной техники, Информатики и Микроэлектроники
Департамент Микроэлектроники и Нанотехнологий

Отчёт
По Объектно-Ориентированному Программированию
по лабораторной работе № 4
“Наследование и композиция”

Выполнил: Цуркану Денис


Группа MN-222
Проверил: V.Mititelu

Кишинев, 2023
Лабораторная работа №4

Тема: Наследование и композиция


Цель работы:
изучение наследования, преимущества и недостатки;
изучение композиции;
изучение правил определения наследования и композиции;
изучение форм наследования;
изучение инициализаторов;
принцип подстановки;
наследование и композиция – что выбрать.
Задание: Вариант - 12
а) Создать иерархию классов Шахматная фигура – абстрактный класс,
содержащий поле – цвет. Создать производные классы все фигуры,
содержащие свое название и координаты позиции на доске. Для
задания текстовых полей использовать оператор new. Переопределить
вывод в поток и ввод из потока, конструктор копирования, оператор
присваивания через соответствующие функции базового класса.
b) Создать класс Шахматы, состоящее из набора фигур из задания а, и
шахматной доски – двумерный массив 8 на 8. Должна быть
возможность удаления фигур с поля. Определить конструктор,
динамически создающий фигуры и задающий их позиции в
шахматной нотации (Е2). Определить конструктор копий и оператор
присваивания.
Код программы:
Вариант a):
#include <iostream>
#include <cstring>

using namespace std;

class Figure{
private:
char *color;
public:
Figure(){
color = new char[0];
}
Figure(const char *c){
color = new char[strlen(c)+1];
strcpy(color, c);
}
Figure(const Figure &Obj){
color = new char[strlen(Obj.color) + 1];
strcpy(color, Obj.color);
}
~Figure(){
if(color)
delete[] color;
}
Figure &operator=(const Figure &Obj){
if(this == &Obj)
return *this;
if(color)
delete[] color;
color = new char[strlen(Obj.color) + 1];
strcpy(color, Obj.color);
return *this;
}
friend ostream &operator<<(ostream &out, const Figure &Obj){
out << "Color: " << Obj.color;
return out;
}
friend istream &operator>>(istream &in, Figure &Obj){
char temp[10];
cout << "Enter color: ";
in >> temp;
if(Obj.color)
delete[] Obj.color;
Obj.color = new char[strlen(temp) + 1];
strcpy(Obj.color, temp);
return in;
}
};

class All: public Figure{


private:
char x;
int y;
char *name;
public:
All() : Figure(){
x = '\0';
y = -1;
name = nullptr;
}
All(const char *n, const char *color) : Figure(color){
name = new char[strlen(n) + 1];
strcpy(name, n);
x = '0';
y = 0;
}
All(const char *n,const char *color,char X, int Y) : Figure(color){
name = new char[strlen(n) + 1];
strcpy(name, n);
while(X > 'h' || X < 'a'){
cout << "Incorrect data for x coordinate, please enter the correct data: ";
cin >> X;
}
x = X;
while(Y > 8 || Y < 0){
cout << "Incorrect data for y coordinate, please enter the correct data: ";
cin >> Y;
}
y = Y;
}
All(const All &Obj) : Figure(Obj){
x = Obj.x;
y = Obj.y;
name = new char[strlen(Obj.name) + 1];
strcpy(name, Obj.name);
}
~All(){
if(name)
delete[] name;
}
All &operator=(const All &Obj){
if(this == &Obj)
return *this;
Figure::operator=(Obj);
x = Obj.x;
y = Obj.y;
if(name)
delete[] name;
name = new char[strlen(Obj.name) + 1];
strcpy(name, Obj.name);
return *this;
}
friend ostream &operator<<(ostream &out, const All &Obj){
out << "Name: " << Obj.name << endl;
out << (static_cast<Figure>(Obj)) << endl;
out << "Coordinates: " << Obj.x << Obj.y << endl;
return out;
}
friend istream &operator>>(istream &in, All &Obj){
char temp[20];
char X;
int Y;
cout << "Enter name: ";
in >> temp;
Obj.name = new char[strlen(temp) + 1];
strcpy(Obj.name, temp);
in >> (static_cast<Figure &>(Obj));
cout << "Enter coordinates: " << endl;
cout << "x = "; in >> X;
while(X > 'h' || X < 'a'){
cout << "Incorrect data for x coordinate, please enter the correct data: ";
in >> X;
}
Obj.x = X;
cout << "y = "; in >> Y;
while(Y > 8 || Y < 0){
cout << "Incorrect data for y coordinate, please enter the correct data: ";
in >> Y;
}
Obj.y = Y;
return in;
}
};
int main(){
All pawn("pawn", "black", 'e', 9);
All king("King", "White");
All queen("Queen", "Black", 'c', 6);
All q2("queen", "white", 'f', 7);
All f1;

cout << "Enter data for you figure: " << endl;
cin >> f1;
system("cls");

cout << pawn << endl;


cout << king << endl;
cout << queen << endl;
queen = q2;
cout << queen;
system("pause");
}
Вывод программы:
Вариант a):
Код программы:
Вариант b):
#include <iostream>
#include <cstring>

using namespace std;

class Figure{
public:
char *color;
char *name;
char x;
int y;

Figure(){
color = new char[0];
x = '\0';
y = -1;
name = nullptr;
}
Figure(const char *n, const char *c){
color = new char[strlen(c)+1];
strcpy(color, c);
name = new char[strlen(n) + 1];
strcpy(name, n);
x = '0';
y = 0;
}
Figure(const char *n,const char *c,char X, int Y){
name = new char[strlen(n) + 1];
strcpy(name, n);
color = new char[strlen(c)+1];
strcpy(color, c);
while(X > 'h' || X < 'a'){
cout << "Incorrect data for x coordinate, please enter the correct data: ";
cin >> X;
}
x = X;
while(Y > 8 || Y < 0){
cout << "Incorrect data for y coordinate, please enter the correct data: ";
cin >> Y;
}
y = Y;
}
Figure(const Figure &Obj){
color = new char[strlen(Obj.color) + 1];
strcpy(color, Obj.color);
x = Obj.x;
y = Obj.y;
name = new char[strlen(Obj.name) + 1];
strcpy(name, Obj.name);
}
~Figure(){
if(color)
delete[] color;
if(name)
delete[] name;
}
Figure &operator=(const Figure &Obj){
if(this == &Obj)
return *this;
if(color)
delete[] color;
color = new char[strlen(Obj.color) + 1];
strcpy(color, Obj.color);
x = Obj.x;
y = Obj.y;
if(name)
delete[] name;
name = new char[strlen(Obj.name) + 1];
strcpy(name, Obj.name);
return *this;
}
friend ostream &operator<<(ostream &out, const Figure &Obj){
out << "Name: " << Obj.name << endl;
out << "Color: " << Obj.color;
out << "Coordinates: " << Obj.x << Obj.y << endl;
return out;
}
friend istream &operator>>(istream &in, Figure &Obj){
char tempColor[10];
char tempName[20];
char X;
int Y;
cout << "Enter name: ";
in >> tempName;
Obj.name = new char[strlen(tempName) + 1];
strcpy(Obj.name, tempName);
cout << "Enter color: ";
in >> tempColor;
if(Obj.color)
delete[] Obj.color;
Obj.color = new char[strlen(tempColor) + 1];
strcpy(Obj.color, tempColor);
cout << "Enter coordinates: " << endl;
cout << "x = "; in >> X;
while(X > 'h' || X < 'a'){
cout << "Incorrect data for x coordinate, please enter the correct data: ";
in >> X;
}
Obj.x = X;
cout << "y = "; in >> Y;
while(Y > 8 || Y < 0){
cout << "Incorrect data for y coordinate, please enter the correct data: ";
in >> Y;
}
Obj.y = Y;
return in;
}
};

class ChessTable{
private:
string Table[8][8];
public:
ChessTable(){
for(size_t i = 0; i < 8; ++i){
for(size_t j = 0; j < 8; ++j){
if ((i + j) % 2 == 0)
Table[i][j] = "* ";
else
Table[i][j] = " ";
}
}
}
void addFigure(Figure &Obj){
int X;
if(Obj.x == 'a')
X = 0;
if(Obj.x == 'b')
X = 1;
if(Obj.x == 'c')
X = 2;
if(Obj.x == 'd')
X = 3;
if(Obj.x == 'e')
X = 4;
if(Obj.x == 'f')
X = 5;
if(Obj.x == 'g')
X = 6;
if(Obj.x == 'h')
X = 7;
if(!strcmpi(Obj.name, "king")){
if(!strcmpi(Obj.color, "white"))
Table[Obj.y-1][X] = "K ";
else if(!strcmpi(Obj.color, "black"))
Table[Obj.y-1][X] = "k ";
}
if(!strcmpi(Obj.name, "queen")){
if(!strcmpi(Obj.color, "white"))
Table[Obj.y-1][X] = "Q ";
else if(!strcmpi(Obj.color, "black"))
Table[Obj.y-1][X] = "q ";
}
if(!strcmpi(Obj.name, "bishop")){
if(!strcmpi(Obj.color, "white"))
Table[Obj.y-1][X] = "B ";
else if(!strcmpi(Obj.color, "black"))
Table[Obj.y-1][X] = "b ";
}
if(!strcmpi(Obj.name, "knight")){
if(!strcmpi(Obj.color, "white"))
Table[Obj.y-1][X] = "N ";
else if(!strcmpi(Obj.color, "black"))
Table[Obj.y-1][X] = "n ";
}
if(!strcmpi(Obj.name, "rook")){
if(!strcmpi(Obj.color, "white"))
Table[Obj.y-1][X] = "R ";
else if(!strcmpi(Obj.color, "black"))
Table[Obj.y-1][X] = "r ";
}
if(!strcmpi(Obj.name, "pawn")){
if(!strcmpi(Obj.color, "white"))
Table[Obj.y-1][X] = "P ";
else if(!strcmpi(Obj.color, "black"))
Table[Obj.y-1][X] = "p ";
}
}
void removeFigure(const char x, const int Y) {
if (x > 'h' or x < 'a') {
cout << "Index X out of range" << endl;
return;
}
if(Y > 8 or Y < 1){
cout << "Index Y out of range" << endl;
return;
}
int xTemp;
if(x == 'a')
xTemp = 0;
if(x == 'b')
xTemp = 1;
if(x == 'c')
xTemp = 2;
if(x == 'd')
xTemp = 3;
if(x == 'e')
xTemp = 4;
if(x == 'f')
xTemp = 5;
if(x == 'g')
xTemp = 6;
if(x == 'h')
xTemp = 7;

if ((xTemp + Y - 1) % 2 == 0)
Table[Y-1][xTemp] = "* ";
else
Table[Y-1][xTemp] = " ";
}

void print(){
for(size_t i = 7; (i >= 0 and i < 8); --i){
for(size_t j = 0; j < 8; ++j){
cout << Table[i][j];
}
cout << (1+i) << endl;
}
cout << "a b c d e f g h" << endl;
}
};

int main(){
ChessTable chess;
unsigned short cmd;
Figure fig;
start:
system("cls");
chess.print();
cout << "\nChoose a command: " << endl
<< "1.Add figure" << endl
<< "2.Remove figure" << endl
<< "3.Info" << endl
<< "4.Exit program" << endl;
cin >> cmd;
switch(cmd){
case 1:{
case_1:
system("cls");
chess.print();
cout << "\nEnter figure you want to add(e.g. king, white, e, 5)" << endl;
cin >> fig;
chess.addFigure(fig);
system("cls");
chess.print();
cout << "\nWant to add another figure? [1/0]: ";
unsigned short newF;
cin >> newF;
if(newF)
goto case_1;
break;
}
case 2:{
case_2:
system("cls");
chess.print();
char x;
int y;
cout << "\nEnter position of figure you want to delete(e.g. e, 5)" << endl;
cin >> x >> y;
chess.removeFigure(x, y);
system("cls");
chess.print();
cout << "\nWant to remove another figure? [1/0]: ";
unsigned short removeF;
cin >> removeF;
if(removeF)
goto case_2;
break;
}
case 3:{
system("cls");
cout << "Information about this program" << endl
<< endl
<< "1. Name of all figures: \nKing \nQueen \nBishop \nKnight \nRook \nPawn
\n" <<endl
<< "2. Figures and their colors can be written in any register " << endl
<< "(e.g. kInG BlAck <- program will understand this)" << endl
<< "3.This is not playable chess" << endl;
break;
}
default:{
system("cls");
cout << "Successfully finished the program" << endl;
system("pause");
return 0;
}
}
unsigned short exit;
cout << "\nWant to continue/exit the program? [1/0]: ";
cin >> exit;
if(exit){
goto start;
}
cout << "Successfully finished the program" << endl;
system("pause");
return 0;
}
Вывод программы:
Вариант b):
1.Add figure
2.Remove figure

3.Info
Вывод:
Выполняя данную лабораторную работу мы приобрели
практические навыки в написании программ с использованием
наследования и композиции.

Вам также может понравиться