forked from teseoch/CPP-Fall-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path91-rectangle_square.cpp
106 lines (86 loc) · 2.07 KB
/
91-rectangle_square.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <stdexcept>
#include <string>
class Rectangle
{
public:
Rectangle()
{
width = 0;
height = 0;
name = "Private dont touch me";
}
Rectangle(double initial_width, double initial_height)
{
width = initial_width;
height = initial_height;
name = "Private dont touch me";
}
void set_width(double w)
{
width = w;
}
double get_width()
{
return width;
}
double get_height()
{
return height;
}
double get_area()
{
return get_width() * get_height();
}
protected:
double width;
double height;
private:
std::string name;
friend std::ostream &operator<<(std::ostream &stream, Rectangle &R);
};
//An operator to allow Rectangle objects to be output directly into streams.
std::ostream &operator<<(std::ostream &stream, Rectangle &R)
{
stream << "Rectangle: " << R.get_width() << " x " << R.get_height();
stream << " (area = " << R.get_area() << ")";
stream << " (name = " << R.name << ")";
return stream;
}
class Square : public Rectangle
{
public:
Square(double side_length)
{
width = side_length;
height = side_length;
// name = "hehe i am touching";
}
void change_side_length(double side_length)
{
width = side_length;
height = side_length;
}
double get_side_length()
{
return width;
}
};
int main()
{
Rectangle R{6, 10};
Square S{10};
std::cout << R << std::endl;
/* Task: Make the code below work for Squares by
defining a Square to be a specialization
of Rectangle.*/
std::cout << S << std::endl;
std::cout << "Area of S: " << S.get_area() << std::endl;
std::cout << "Side length of S: " << S.get_side_length() << std::endl;
S.change_side_length(2);
// S.set_width(4);
std::cout << S << std::endl;
std::cout << "Area of S: " << S.get_area() << std::endl;
std::cout << "Side length of S: " << S.get_side_length() << std::endl;
return 0;
}