Skip to content

Commit 0aea357

Browse files
author
XuhuaHuang
committed
Refactor modern rectangle example
1 parent a3c4b4d commit 0aea357

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* @file modern_square_rectangle.cpp
3+
* @author Xuhua Huang
4+
* @brief
5+
* @version 0.1
6+
* @date 2026-04-04
7+
*
8+
* @copyright Copyright (c) 2026
9+
*
10+
*/
11+
12+
#include <iostream>
13+
14+
class rectangle_t {
15+
private:
16+
int width{0};
17+
int height{0};
18+
19+
public:
20+
constexpr inline rectangle_t() = default;
21+
22+
constexpr inline rectangle_t(int w, int h)
23+
: width(w)
24+
, height(h) {}
25+
26+
void set_width(int w) noexcept { width = w; }
27+
void set_height(int h) noexcept { height = h; }
28+
29+
[[nodiscard]]
30+
int get_width() const noexcept {
31+
return width;
32+
}
33+
34+
[[nodiscard]]
35+
int get_height() const noexcept {
36+
return height;
37+
}
38+
39+
[[nodiscard]]
40+
int area() const noexcept {
41+
return width * height;
42+
}
43+
44+
// Preferred: member function instead of friend
45+
[[nodiscard]]
46+
rectangle_t double_in_size() const noexcept {
47+
return rectangle_t(width * 2, height * 2);
48+
}
49+
};
50+
51+
// Optional: keep a free function wrapper if needed
52+
[[nodiscard]]
53+
rectangle_t double_in_size(const rectangle_t& rect) noexcept {
54+
return rect.double_in_size();
55+
}
56+
57+
int main() {
58+
rectangle_t r1;
59+
rectangle_t r2(2, 3);
60+
61+
r1 = double_in_size(r2);
62+
63+
std::cout << r1.area() << std::endl;
64+
65+
return 0;
66+
}

0 commit comments

Comments
 (0)