Скачиваний:
0
Добавлен:
22.09.2026
Размер:
57 Кб
Скачать
☆

ФЕДЕРАЛЬНОЕ АГЕНТСТВО СВЯЗИ

ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ

«САНКТ-ПЕТЕРБУРГСКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ ТЕЛЕКОММУНИКАЦИЙ ИМ. ПРОФ. М.А. БОНЧ-БРУЕВИЧА»

(СПбГУТ)

Факультет информационных технологий и программной инженерии (ИТПИ)

Кафедра программной инженерии и вычислительной техники (ПИиВТ)

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

Лабораторная работа №1.

Выполнил: Студент группы ИКПИ-41

Летягина Е. А.

Подпись

Принял: Доцент кафедры ПИиВТ

Коробов С. А.

Подпись

«_____»________ 2025

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

2025 г.

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

Вариант: 14

Номера заданий: 2, 14

Задание 2:

Необходимо разработать класс для обработки векторов. В разрабатываемом классе математический вектор реализуется на основе динамического массива. Тип элементов, хранящихся в массиве, выбирается студентом самостоятельно. Класс должен содержать поле для хранения размерности вектора.

Над объектами разрабатываемого класса должны быть предусмотрены следующие основные операции:

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

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

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

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

Задание 14:

Необходимо разработать класс для работы с рациональными числами. Разработанный класс (Rational) должен обеспечить выполнение следующих операций:

  • конструктор умолчания.

  • конструктор с параметрами.

  • сложение,

  • вычитание,

  • умножение,

  • деление,

  • сравнения на равенство и неравенство.

  • отношения.

  • вывод рационального числа на экран дисплея.

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

lab1.cpp

#include "classes.h"

#include <iostream>

#include <cstdlib>

using namespace std;

int main() {

//----------Задание 3-------------//

    cout << "//----------Task 3-------------//" << endl;

    cout << endl;

    const size_t N = 3;

    Vector v1(N), v2(N);

   

    // Заполняем векторы случайными значениями

    for (size_t i = 0; i < N; ++i) {

        v1[i] = rand() % 100;

        v2[i] = rand() % 100;

    }

   

    cout << "Vector1: ";

    v1.print();

    cout << "Vector2: ";

    v2.print();

    cout << endl;

    // Сложение векторов

    cout << "Summation: ";

    Vector v3 = v1 + v2;

    v3.print();

    cout << endl;

    // Вычитание векторов

    cout << "Subtraction: ";

    Vector v4 = v1 - v2;

    v4.print();

    cout << endl;

    // Поэлементное умножение

    cout << "Element-wise multiplication: ";

    Vector v5 = v1 * v2;

    v5.print();

    cout << endl;

   

    // Вычисление длины

    cout << "Length of v1: " << v1.length() << endl;

    cout << "Length of v2: " << v2.length() << endl;

    cout << endl;

//----------Задание 14-------------//

    cout << "//----------Task 14-------------//" << endl;

    cout << endl;

    Rational a(rand() % 100, rand() % 100);

    Rational b(rand() % 100, rand() % 100);

    cout << "Rational a: "; a.print();

    cout << "Rational b: "; b.print();

    cout << endl;

    cout << "Summation: "; (a + b).print();

    cout << "Subtraction: "; (a - b).print();

    cout << "Multiplication: "; (a * b).print();

    cout << "Division: "; (a / b).print();

    cout << endl;

    cout << "a == b: " << (a == b? "true" : "false") << endl;

    cout << "a != b: " << (a != b? "true" : "false") << endl;

    cout << "a > b: " << (a > b? "true" : "false") << endl;

    cout << "a >= b: " << (a >= b? "true" : "false") << endl;

    cout << "a < b: " << (a < b ? "true" : "false") << endl;

    cout << "a <= b: " << (a <= b ? "true" : "false") << endl;

   

    return 0;

}

classes.h

#ifndef CLASSES_H

#define CLASSES_H

#include <cstdlib>

#include <iostream>

#include <stdexcept>

//----------Задание 3-------------//

class Vector {

private:

    size_t size_;

    double* data_ = nullptr;

public:

    // Конструктор

    Vector(size_t size);

   

    // Деструктор

    ~Vector();

   

    // Конструктор копирования

    Vector(const Vector& other);

   

    // Метод получения размера

    size_t size() const;

   

    // Метод печати

    void print();

   

    // Оператор индексирования

    double& operator[](size_t index);

   

    // Оператор присваивания

    Vector& operator=(const Vector& other);

   

    // Оператор сложения

    Vector operator+(const Vector& other);

   

    // Оператор вычитания

    Vector operator-(const Vector& other);

   

    // Оператор умножения (поэлементное)

    Vector operator*(const Vector& other);

   

    // Метод вычисления длины

    double length();

};

//----------Задание 14-------------//

class Rational{

    private:

        int numerator_;

        int denominator_;

    public:

        // Конструктор

        Rational();

        // Конструктор с параметрами

        Rational(int p, int q = 1);

        // Конструктор копирования

        Rational(const Rational& other);

        // Деструктор

        ~Rational();

        int numerator() const;

        int denominator() const;

        void reduce();

        // Арифметические операции

        Rational operator+(const Rational& other);

        Rational operator-(const Rational& other);

        Rational operator*(const Rational& other);

        Rational operator/(const Rational& other);

        // Операторы сравнения

        bool operator==(const Rational& other) const;

        bool operator!=(const Rational& other) const;

        bool operator>(const Rational& other) const;

        bool operator>=(const Rational& other) const;

        bool operator<(const Rational& other) const;

        bool operator<=(const Rational& other) const;

        // Метод печати

        void print();

};  

#endif // CLASSES_H

classes.cpp

#include "classes.h"

#include <algorithm>

#include <cmath>

#include <iostream>

#include <stdexcept>

using namespace std;

//----------Задание 3-------------//

// Конструктор

Vector::Vector(size_t size) {

    size_ = size;

    data_ = new double[size];

    // Инициализируем нулями

    for (size_t i = 0; i < size_; ++i) {

        data_[i] = 0.0;

    }

}

// Деструктор

Vector::~Vector() {

    delete[] data_;

}

// Конструктор копирования

Vector::Vector(const Vector& other) : Vector(other.size_) {

    copy(other.data_, other.data_ + size_, data_);

}

// Метод получения размера

size_t Vector::size() const {

    return size_;

}

// Метод печати

void Vector::print() {

    for (size_t i = 0; i < size_; i++) {

        cout << data_[i] << " ";

    }

    cout << endl;

}

// Оператор индексирования

double& Vector::operator[](size_t index) {

    if (index >= size_) {

        throw out_of_range("Index out of range");

    }

    return data_[index];

}

// Оператор присваивания

Vector& Vector::operator=(const Vector& other) {

    if (this != &other) {

        delete[] data_;

        size_ = other.size_;

        data_ = new double[size_];

        copy(other.data_, other.data_ + size_, data_);

    }

    return *this;

}

// Оператор сложения

Vector Vector::operator+(const Vector& other) {

    if (size_ != other.size_) {

        throw invalid_argument("Vectors must have the same size");

    }

    Vector result(size_);

    for (size_t i = 0; i < size_; i++) {

        result[i] = data_[i] + other.data_[i];

    }

    return result;

}

// Оператор вычитания

Vector Vector::operator-(const Vector& other) {

    if (size_ != other.size_) {

        throw invalid_argument("Vectors must have the same size");

    }

    Vector result(size_);

    for (size_t i = 0; i < size_; i++) {

        result[i] = data_[i] - other.data_[i];

    }

    return result;

}

// Оператор умножения (поэлементное)

Vector Vector::operator*(const Vector& other) {

    if (size_ != other.size_) {

        throw invalid_argument("Vectors must have the same size");

    }

    Vector result(size_);

    for (size_t i = 0; i < size_; i++) {

        result[i] = data_[i] * other.data_[i];

    }

    return result;

}

// Метод вычисления длины

double Vector::length() {

    double result = 0;

    for (size_t i = 0; i < size_; i++) {

        result += data_[i] * data_[i];

    }

    return sqrt(result);

}

//----------Задание 14-------------//

// Конструкторы

Rational::Rational(): numerator_(0), denominator_(1) {}

Rational::Rational(int p, int q) : numerator_(p), denominator_(q) {

    if (q == 0){

        throw invalid_argument("Denominator cannot be zero");

    }

    reduce();

}

Rational::~Rational() {}

// Конструктор копирования

Rational::Rational(const Rational& other) : numerator_(other.numerator_), denominator_(other.denominator_) {}

int Rational::numerator() const{

    return numerator_;

}

int Rational::denominator() const{

    return denominator_;

}

// Метод сокращения

void Rational:: reduce(){

    if (denominator_ == 0){

        return;

    }

    int gcd = __gcd(numerator_, denominator_);

    numerator_ /= gcd;

    denominator_ /= gcd;

    if (denominator_ < 0){

        numerator_ *= -1;

        denominator_ *= -1;

    }

}

// Оператор сложения

Rational Rational::operator+(const Rational& other) {

    int p = numerator_ * other.denominator_ + denominator_ * other.numerator_;

    int q = denominator_ * other.denominator_;

    return Rational(p, q);

}

// Оператор вычитания

Rational Rational::operator-(const Rational& other) {

    int p = numerator_ * other.denominator_ - denominator_ * other.numerator_;

    int q = denominator_ * other.denominator_;

    return Rational(p, q);

}

// Оператор умножения

Rational Rational::operator*(const Rational& other) {

    int p = numerator_ * other.numerator_;

    int q = denominator_ * other.denominator_;

    return Rational(p, q);

}

// Оператор деления

Rational Rational::operator/(const Rational& other) {

    if (other.numerator_ == 0){

        throw invalid_argument("Denominator cannot be zero");

    }

    int p = numerator_ * other.denominator_;

    int q = denominator_ * other.numerator_;

    return Rational(p, q);

}

// Операторы сравнения

bool Rational::operator==(const Rational& other) const {

    return numerator_ * other.denominator_ == denominator_ * other.numerator_;

}

bool Rational::operator!=(const Rational& other) const {

    return numerator_ * other.denominator_ != denominator_ * other.numerator_;

}

bool Rational::operator>(const Rational& other) const {

    return numerator_ * other.denominator_ > denominator_ * other.numerator_;

}

bool Rational::operator>=(const Rational& other) const {

    return numerator_ * other.denominator_ >= denominator_ * other.numerator_;

}

bool Rational::operator<(const Rational& other) const {

    return numerator_ * other.denominator_ < denominator_ * other.numerator_;

}

bool Rational::operator<=(const Rational& other) const {

    return numerator_ * other.denominator_ <= denominator_ * other.numerator_;

}

void Rational:: print() {

    if (denominator_ == 1){

        cout << numerator_ << endl;

        return;

    }

    else{

        cout << numerator_ << "/" << denominator_ << endl;

        return;

    }

}

  1. Вывод программы