Отчеты по лабам / Лаб 1 Вар 9
.docxОбъектно-ориентированное программирование. Лабораторная работа №1. Зарецкий Даниил, вариант №9.
Постановка задачи
Цель настоящей работы состоит в ознакомлении с правилами организации классов, принятыми при программировании на языке C++. В процессе выполнения лабораторной работы необходимо разработать два класса и написать тестовые программы для демонстрации их работоспособности.
Даны варианты №9 и №15. В варианте №9 необходимо разработать класс Array, предназначенный для работы с массивами. Разрабатываемый класс должен предусматривать выполнение следующих операций:
копирование массивов,
ввод элементов массива с клавиатуры,
вывод элементов массива на экран дисплея,
добавка элемента в конец занятой части массива,
вставка одного массива в заданную позицию другого,
вычисление значения наибольшего элемента массива.
В варианте №15 необходимо разработать класс ComplexNumber, предназначенный для работы с комплексными числами. Класс должен поддерживать выполение следующих операций:
Сложение;
Вычитание;
Умножение;
Деление;
Вывод комплексного числа на экран дисплея.
Код
ComplexNumber:
ComplexNumber.h:
#pragma once
#include <iostream>
class ComplexNumber {
private:
double a; // Реальная часть КЧ
double b; // Мнимая часть КЧ
public:
ComplexNumber();
ComplexNumber(int a, int b);
using CN = ComplexNumber;
const CN operator+(const CN& cn) const;
const CN operator-(const CN& cn) const;
const CN operator*(const CN& cn) const;
const CN operator/(const CN& cn) const;
CN& operator=(const CN& rhs);
void Print() const;
};
void PrintCN(const ComplexNumber& cn, int number);
void PrintCN(const ComplexNumber& cn1, int n1, const ComplexNumber& cn2, int n2);
ComplexNumber.cpp:
#include <iostream>
#include <iomanip>
#include <cmath>
#include "ComplexNumber.h"
ComplexNumber::ComplexNumber() : a(0), b(0) { }
ComplexNumber::ComplexNumber(int a, int b) : a(a), b(b) { }
const ComplexNumber ComplexNumber::operator+(const ComplexNumber& cn) const { return ComplexNumber(a + cn.a, b + cn.b); }
const ComplexNumber ComplexNumber::operator-(const ComplexNumber& cn) const { return ComplexNumber(a - cn.a, b - cn.b); }
const ComplexNumber ComplexNumber::operator*(const ComplexNumber& cn) const {
double new_a = a * cn.a - b * cn.b;
double new_b = a * cn.b + b * cn.a;
return ComplexNumber(new_a, new_b);
}
const ComplexNumber ComplexNumber::operator/(const ComplexNumber& cn) const {
// Предполагается, что значения a и b у cn ненулевые
double z = cn.a * cn.a + cn.b * cn.b;
double new_a = (a * cn.a + b * cn.b) / z;
double new_b = (b * cn.a - a * cn.b) / z;
return ComplexNumber(new_a, new_b);
}
ComplexNumber& ComplexNumber::operator=(const ComplexNumber& rhs) {
if (this == &rhs)
return *this;
a = rhs.a;
b = rhs.b;
return *this;
}
void ComplexNumber::Print() const {
std::cout << std::setprecision(3) << a << ' '
<< (b > 0 ? '+' : '-') << ' '
<< std::setprecision(3) << std::abs(b)
<< 'i';
// std::cout << std::endl;
}
void PrintCN(const ComplexNumber& cn, int number) {
std::cout << "cn" << number << " = ";
cn.Print();
std::cout << std::endl;
}
void PrintCN(const ComplexNumber& cn1, int n1, const ComplexNumber& cn2, int n2) {
PrintCN(cn1, n1);
PrintCN(cn2, n2);
}
ComplexNumber_main.cpp:
#include <iostream>
#include <iomanip>
#include <cmath>
#include "ComplexNumber.h"
void TestComplexNumber() {
ComplexNumber cn1(3, 4);
ComplexNumber cn2(8, 6);
PrintCN(cn1, 1, cn2, 2);
std::cout << std::endl;
// Сложение и вычитание
ComplexNumber cn3 = cn1 + cn2;
ComplexNumber cn4 = cn1 - cn2;
PrintCN(cn3, 3, cn4, 4);
std::cout << std::endl;
// Умножение и деление
ComplexNumber cn5 = cn1 * cn2;
ComplexNumber cn6 = cn2 / cn1;
PrintCN(cn5, 5, cn6, 6);
std::cout << std::endl;
}
int main() {
std::cout << "[---] Lab1. Task: class \"Complex Number\", variant 15 [---]" << std::endl << std::endl;
TestComplexNumber();
std::cout << "[---] End [---]" << std::endl;
return 0;
}
Array:
Array.h:
#pragma once
class Array
{
public:
Array(int n);
void ArrayCopy(const Array& rhs);
void arrayInput();
void arrayOutput();
void elementInput(int inputElement);
void InputArray1ToArray2(const Array& array2, int pos);
int findMaxArrayEl(const Array& array1);
private:
int arrayElementsAmount;
int* arr;
};
Array.cpp:
#include "Array.h"
#pragma once
#include <iostream>
using namespace std;
Array::Array(int n) : arrayElementsAmount(n), arr(new int [n]) {}
void Array::ArrayCopy(const Array& rhs){
delete [] arr;
arrayElementsAmount = rhs.arrayElementsAmount;
arr = new int[arrayElementsAmount];
for (int i = 0; i < arrayElementsAmount; i++) {
arr[i] = rhs.arr[i];
}
}
void Array::arrayInput() {
for (int i = 0; i < arrayElementsAmount; i++) cin >> arr[i];
}
void Array::arrayOutput() {
for (int i = 0; i < arrayElementsAmount; i++) cout << arr[i] << " ";
}
void Array::elementInput(int inputElement) {
int* newArr = new int[arrayElementsAmount + 1];
for (int i = 0; i < arrayElementsAmount; i++) newArr[i] = arr[i];
newArr[arrayElementsAmount++] = inputElement;
delete[] arr;
arr = newArr;
}
void Array::InputArray1ToArray2(const Array& array2, int pos) {
int* newArr = new int[array2.arrayElementsAmount + arrayElementsAmount];
for (int i = 0; i < pos; i++) newArr[i] = arr[i];
for (int i = 0; i < array2.arrayElementsAmount; i++) newArr[i+pos] = array2.arr[i];
for (int i = pos+array2.arrayElementsAmount; i < (arrayElementsAmount + array2.arrayElementsAmount); i++) newArr[i] = arr[i - array2.arrayElementsAmount];
delete[] arr;
arr = newArr;
arrayElementsAmount += array2.arrayElementsAmount;
}
int Array::findMaxArrayEl(const Array& array1) {
int max = -INFINITY;
for (int i = 0; i < arrayElementsAmount; i++)
if (arr[i] > max) max = arr[i];
return max;
delete[] arr;
}
main.cpp:
#include <iostream>
#include "Array.h"
using namespace std;
int main()
{
Array array1(5), array2(5);
cout << "Input 1st array elements: " << endl;
array1.arrayInput();
cout << "Input 2nd array elements: " << endl;
array2.arrayInput();
cout << "Copying array 2 to array 1... " << endl;
array1.ArrayCopy(array2);
cout << "Array1 after copying is: ";
array1.arrayOutput();
cout << endl;
int inputElement = 555;
cout << "Adding element in the end of the array: ";
array1.elementInput(inputElement);
array1.arrayOutput();
cout << endl;
int pos = 5;
cout << "Copying array2 to pos [1] of array1: ";
array1.InputArray1ToArray2(array2, 1);
array1.arrayOutput();
cout << endl;
cout << "Max element of array1 is: ";
cout << array1.findMaxArrayEl(array1);
cout << endl;
cout << "All done!" << endl;
}
Скриншоты работы программы