Скачиваний:
2
Добавлен:
15.08.2023
Размер:
42.95 Кб
Скачать

ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ "САНКТ-ПЕТЕРБУРГСКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ ТЕЛЕКОММУНИКАЦИЙ ИМ. ПРОФ. М. А. БОНЧ-БРУЕВИЧА"

Факультет инфокоммуникационных сетей и систем

Кафедра сетей связи и передачи данных

ЛАБОРАТОРНАЯ РАБОТА №1

«КЛАССЫ»

по дисциплине «Объектно-ориентированное программирование»

Выполнили:

студент 2-го курса

дневного отделения

группы ИКПИ-92

Козлов Никита

Санкт-Петербург

2020

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

Цель настоящей работы состоит в ознакомлении студента с правилами организации классов, принятыми при программировании на языке С++. В процессе выполнения настоящей работы каждый студент должен разработать два класса и написать тестовые программы для демонстрации их работоспособности.

    1. Вариант задачи

Номер

Задачи

13

1 и 16

    1. Задачи

  1. Математический вектор

В математике широко используется понятие вектора. В этом

разделе приводятся формулировки двух задач, которые отличаются

требованиями к реализации разрабатываемого вектора. Над

объектами разрабатываемого класса в каждой из этих задач должны

быть предусмотрены следующие основные операции:

- сложение векторов,

- вычитание векторов,

- вычисление скалярного произведения векторов,

- вычисление длины вектора.

Математический вектор реализуется на основе статического

массива. Тип элементов, хранящихся в массиве, выбирается

студентом самостоятельно. Класс должен содержать поле для

хранения размерности вектора.

  1. Комплексные числа

В этих задачах требуется разработать класс, обеспечивающий работу с комплексными числами. Задачи отличаются своей реализацией. В задаче 15 реализация должна содержать два поля, определяющие соответственно действительную и мнимую часть комплексного числа. В задаче 16 реализация должна содержать три поля. Первое и втрое поле должны задавать само комплексное число (его действительную и мнимую части), а последнее поле должно содержать модуль комплексного числа. Разработанный класс(Complex) должен обеспечить выполнение следующих операций:

- сложение,

- вычитание,

- умножение,

- деление,

- вывод комплексного числа на экран дисплея.

    1. Код программы

Файл comandSource.h

#pragma once

#include <iostream>

#include <math.h>

#include <initializer_list>

#include <assert.h>

//#include <stdexcept>

using namespace std;

namespace mth

{

// Classes

#pragma region Class Vector

/// <summary>

/// Math Vector

/// </summary>

template <typename T>

class Vector

{

private:

size_t length = 0; // length of array

T* buffer = NULL; // array eq to null pointer

public:

Vector(); // Default constructor

Vector(const Vector& r); // Copy constuctor

Vector(int _length); // Constructor with given length

~Vector() { delete[] buffer; buffer = NULL; }; // Destructor

void print(); // Print each element of Vector array

size_t len(void) { return length; } // Returns legth of Vector array

template<typename U> friend U dot_product(const Vector<U>& v1, const Vector<U>& v2);

Vector operator = (const Vector& source);

Vector operator + (const Vector& other);

T& operator [] (const size_t index);

template<typename U> friend Vector<U> operator-(const Vector<U>& v1, const Vector<U>& v2);

};

#pragma endregion

#pragma region Class Complex

/// <summary>

/// Complex digit

/// </summary>

class Complex

{

private:

double reValue;

double iValue;

double r;

public:

Complex(double re, double ir); // Copplex digit constructor

~Complex() { reValue = 0, iValue = 0, r = 0; }; // Complex deconstructor

// All operator are reloaded in commandSource.cpp file

friend Complex operator + (const Complex& arg1, const Complex& arg2);

friend Complex operator - (const Complex& arg1, const Complex& arg2);

friend Complex operator * (const Complex& arg1, const Complex& arg2);

friend Complex operator / (const Complex& arg1, const Complex& arg2);

void print(); // Print function

double mod(); // Return module of Complex digit

};

#pragma endregion

// Objects

#pragma region Vector objects

template <class T> Vector<T>::Vector()

{

Vector(20);

}

template <typename T> Vector<T>::Vector(int _length):length(_length)

{

buffer = new T[length];

for (size_t i = 0; i < length; i++)

buffer[i] = 0;

}

template <class T> Vector<T>::Vector(const Vector & arg):length(arg.length)

{

buffer = new T[this->length];

for (size_t i = 0; i < arg.length; i++)

buffer[i] = arg.buffer[i];

}

template<class T> void Vector<T>::print()

{

cout << "{ ";

for (size_t i = 0; i < this->length; i++)

cout << "'" << buffer[i] << "' ";

cout << "}\n";

}

template<typename U> U dot_product(const Vector<U>& v1, const Vector<U>& v2)

{

U res = 0;

assert(v1.length == v2.length && "The arrays lengths must be equal");

for (size_t i = 0; i < v1.length; ++i)

res += v1.buffer[i] * v2.buffer[i];

return res;

}

#pragma endregion

// Operators

#pragma region Vector operators

template<typename T>

Vector<T> Vector<T>::operator=(const Vector& source)

{

length = source.length;

buffer = new T[length];

for (size_t i = 0; i < length; i++)

buffer[i] = source.buffer[i];

return *this;

}

template <typename T>

Vector<T> Vector<T>::operator+(const Vector& arg)

{

if (length != arg.length)

{

cout << "[ERROR] vectors doesn't match by size" << endl;

exit(1);

}

Vector<T>temp(length);

for (size_t i = 0; i < length; i++)

temp.buffer[i] = buffer[i] + arg.buffer[i];

return temp;

}

template<typename T>

T& Vector<T>::operator[](const size_t index)

{

assert(index >= 0 && index < length && "Invalid array index");

return buffer[index];

}

template<typename U>

Vector<U> operator-(const Vector<U>& v1, const Vector<U>& v2)

{

assert(v1.length == v2.length && "The array lengths must be equal");

Vector<U> temp(v1.length);

for (size_t i = 0; i < v1.length; i++)

temp.buffer[i] = v1.buffer[i] - v2.buffer[i];

return temp;

}

#pragma endregion

}

Файл comandSource.cpp

#include "comandSource.h"

#pragma region Complex objects

mth::Complex::Complex(double re, double ir) :reValue(re), iValue(ir)

{

r = sqrt(pow(reValue, 2) + pow(iValue, 2));

}

void mth::Complex::print()

{

cout << reValue << "+" << iValue << "i" << endl;

}

double mth::Complex::mod()

{

return r;

}

#pragma endregion

#pragma region Complex operators

mth::Complex mth::operator + (const Complex& arg1, const Complex& arg2)

{

return Complex(arg1.reValue + arg2.reValue, arg1.iValue + arg2.iValue);

}

mth::Complex mth::operator - (const Complex& arg1, const Complex& arg2)

{

return Complex(arg1.reValue - arg2.reValue, arg1.iValue - arg2.iValue);

}

mth::Complex mth::operator * (const Complex& arg1, const Complex& arg2)

{

return Complex(arg1.reValue * arg2.reValue - arg1.iValue * arg2.iValue, arg1.reValue * arg2.iValue + arg1.iValue * arg2.reValue);

}

mth::Complex mth::operator / (const Complex& arg1, const Complex& arg2)

{

return Complex((arg1.reValue * arg2.reValue + arg1.iValue * arg2.iValue)/pow(arg2.reValue, 2) + pow(arg2.iValue, 2),

(arg1.iValue * arg2.reValue - arg1.reValue * arg2.iValue)/pow(arg2.reValue, 2) + pow(arg2.iValue, 2));

}

#pragma endregion

Файл main.cpp

#include "comandSource.h"

void main()

{

mth::Complex it(2, 3);

mth::Complex is(3, 5);

mth::Complex op(0,0);

op = it + is;

op.print();

op = is - op;

op.print();

op = it * op;

op.print();

op = is / op;

op.print();

mth::Vector<int> Va(3);

mth::Vector<int> Vb(3);

mth::Vector<int> Vc(3);

cout << Va.len() << endl;

cout << Vb.len() << endl;

cout << Vc.len() << endl;

Va[0] = 2;

Va[1] = 4;

Va[2] = 6;

Vb[0] = 4;

Vb[1] = 3;

Vb[2] = 1;

Vc = Va + Vb;

Vc.print();

Vc = Va - Vb;

Vc.print();

}

    1. Работа программы