Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions YuriyKuznetsov_HomeWork8.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// Реализовать переопределение метода базового класса в
//производных классах применив виртуальные функциии
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добрый вечер! по многочисленным просьбам решил опробовать себя в новой роли) поэтому за качество ревью прошу понять и простить)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отлично! Супер! Спасибо за ревью!


#include <cmath>
#include <iostream>

class Shape {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если ошибаюсь, Николай меня поправит, но если мы собираемся работать через указатель на базовый класс и виртуальные функции, то для корректного разрушения объеков в базовом классе нужно обьявить виртуалный деструктор.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

public:
virtual void Draw() = 0;
virtual double CalcSquare() = 0;
};

class Square : public Shape {
public:
void Draw() override;
double CalcSquare() override;

void Side(const unsigned int in_uiSide) { uiSide__ = in_uiSide; }
unsigned int Side() { return uiSide__; }
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eсли метод ничего не меняет, может стоит сделать его const

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ага. Надо завести эту привычку :)


private:
unsigned int uiSide__{};
};

struct RectSides {
unsigned int uiSideOne;
unsigned int uiSideTwo;

RectSides &operator=(const RectSides &in_Sides) {
uiSideOne = in_Sides.uiSideOne;
uiSideTwo = in_Sides.uiSideTwo;
return *this;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а для чего тут перегрузка присваивания? ведь структуры одного типа и так можно присваивать друг другу)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

больше, чтоб поюзать перегрузку операторов.

}
};

class Rectangle : public Shape {
public:
void Draw() override;
double CalcSquare() override;

void Sides(const RectSides in_Sides) { Sides__ = in_Sides; }
RectSides Sides() { return Sides__; }
Comment thread
GKuzzinshtern marked this conversation as resolved.

private:
RectSides Sides__{};
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это просто мнение, но по моему тут не нужна структура, ведь мы и так инкапсулируем поля в классе. А так матрешка получается

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

конечно, можно обойтись и без структуры. Мне понравилась идея передавать все стороны как объект.

};

struct TriangleSides {
unsigned int uiSideOne;
unsigned int uiSideTwo;
unsigned int uiSideThree;

TriangleSides &operator=(const TriangleSides &in_Sides) {
Comment thread
GKuzzinshtern marked this conversation as resolved.
uiSideOne = in_Sides.uiSideOne;
uiSideTwo = in_Sides.uiSideTwo;
uiSideThree = in_Sides.uiSideThree;
return *this;
}
};

class Triangle : public Shape {
public:
void Draw() override;
double CalcSquare() override;

void Sides(const TriangleSides in_Sides) { Sides__ = in_Sides; }
TriangleSides Sides() { return Sides__; }
Comment thread
GKuzzinshtern marked this conversation as resolved.

Triangle() = default;
Triangle(TriangleSides in_Sides) { Sides__ = in_Sides; }

private:
TriangleSides Sides__{};
};

void f(Shape *in_Shape) {
in_Shape->Draw();
in_Shape->CalcSquare();
}

int main() {
Square mySquare{};
mySquare.Side(20);

RectSides SidesForRect{20, 50};
Rectangle myRect{};
myRect.Sides(SidesForRect);

TriangleSides SidesForTriangle{17, 20, 30};
Triangle myTrian(SidesForTriangle);

f(&mySquare);
f(&myRect);
f(&myTrian);

return 0;
}

void Square::Draw() {
std::cout << "Drawing a square with a side: " << uiSide__ << '\n';
}

double Square::CalcSquare() {
double dArea{static_cast<double>(uiSide__) *
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а для чего тут cast к double и возвращаемое значение double? ведь сторона квадрата - целое число. Можно возвращать long long

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в случаях других фигур результат может быть дробным. Поэтому в базовом классе был принят double, а следовательно и в наследниках.

uiSide__}; // without checking for overlimit
std::cout << "The area of the square with a side: " << uiSide__
<< " is: " << dArea << '\n';
return dArea;
}

void Rectangle::Draw() {
std::cout << "Drawing a rectangle with sides: " << Sides__.uiSideOne
<< " and " << Sides__.uiSideTwo << '\n';
}

double Rectangle::CalcSquare() {
double dArea{static_cast<double>(Sides__.uiSideOne) *
Sides__.uiSideTwo}; // without checking for overlimit
std::cout << "The area of the rectangle with sides: " << Sides__.uiSideOne
<< " and " << Sides__.uiSideTwo << " is " << dArea << '\n';
return dArea;
}

void Triangle::Draw() {
std::cout << "Drawing a triangle with sides: " << Sides__.uiSideOne << " , "
<< Sides__.uiSideTwo << " and " << Sides__.uiSideThree << '\n';
}

double Triangle::CalcSquare() {
constexpr double dHalf{1/2};
double dHalfPerimeter{
dHalf * (Sides__.uiSideOne + Sides__.uiSideTwo +
Sides__.uiSideThree)}; // without checking for overlimit
double dArea{std::sqrt(dHalfPerimeter * (dHalfPerimeter - Sides__.uiSideOne) *
(dHalfPerimeter - Sides__.uiSideTwo) *
(dHalfPerimeter - Sides__.uiSideThree))};
std::cout << "The area of the triangle with sides: " << Sides__.uiSideOne
<< " , " << Sides__.uiSideTwo << " and " << Sides__.uiSideThree
<< " is " << dArea << '\n';
return dArea;
}