ãã¾ã
ããè¯ãã³ã¼ãã¨ãã¦ç´¹ä»ããã¦ãã³ã¼ããæ¨æºã©ã¤ãã©ãªã®ç¯å²å ã§æ¸ãç´ãã¦ã¿ããå ¨ãåãããã°ã©ã ãããªããã©ãã©ãããµã³ãã«ãªãã ãç´°ããåä½ã¯ã©ãã§ãããã§ããã
// rectangle.h #pragma once #include <iosfwd> class rectangle { struct impl; impl* pimpl; public: rectangle(); rectangle(const rectangle&); rectangle(int top, int left, int bottom, int right); ~rectangle(); int top() const; int left() const; int bottom() const; int right() const; double area() const; double diagonal_len() const; friend std::ostream& operator<<(std::ostream&, const rectangle&); friend std::istream& operator>>(std::istream&, rectangle&); };
// rectangle.cpp #include "rectangle.h" #include <iostream> #include <cmath> struct rectangle::impl { int top; int left; int bottom; int right; impl(int top, int left, int bottom, int right) : top(top), left(left), bottom(bottom), right(right) {} impl(const impl& other) : top(other.top), left(other.left), bottom(other.bottom), right(other.right) {} }; rectangle::rectangle() : pimpl(new rectangle::impl(0, 0, 0, 0)) {} rectangle::rectangle(const rectangle& other) : pimpl(new rectangle::impl(*other.pimpl)) {} rectangle::rectangle(int top, int left, int bottom, int right) : pimpl(new rectangle::impl(top, left, bottom, right)) {} rectangle::~rectangle() { delete pimpl; } int rectangle::top() const { return pimpl->top; } int rectangle::left() const { return pimpl->left; } int rectangle::bottom() const { return pimpl->bottom; } int rectangle::right() const { return pimpl->right; } namespace { inline int abs(int n) { return n < 0 ? -n : n; } inline int square(int n) { return n * n; } } double rectangle::area() const { return abs(pimpl->top - pimpl->bottom) * abs(pimpl->left - pimpl->right); } double rectangle::diagonal_len() const { return std::sqrt(static_cast<double>(square(pimpl->top - pimpl->bottom) + square(pimpl->left - pimpl->right))); } std::ostream& operator<<(std::ostream& os, const rectangle& rect) { os << "(" << rect.pimpl->top << "," << rect.pimpl->left << ")-(" << rect.pimpl->bottom << "," << rect.pimpl->right << ")ã®é·æ¹å½¢"; return os; } std::istream& operator>>(std::istream& is, rectangle& rect) { is >> rect.pimpl->top >> rect.pimpl->left >> rect.pimpl->bottom >> rect.pimpl->right; return is; }
// main.cpp #include <iostream> #include "rectangle.h" void print_rectangle(std::ostream& os, const rectangle& rect) { os << rect << '\n' << "é¢ç©ï¼" << rect.area() << '\n' << "対è§ç·ã®é·ãï¼" << rect.diagonal_len() << std::endl; } int main() { rectangle rect; std::cout << "座æ¨ãå ¥åãã¦ãã ãã(top left bottom right): "; std::cin >> rect; print_rectangle(std::cout, rect); std::cout << "æ°ããé·æ¹å½¢" << std::endl; int newbottom, newright; std::cout << "æ°ããé·æ¹å½¢ã®å³ä¸ã®åº§æ¨ãå ¥åãã¦ãã ãã(bottom right):"; std::cin >> newbottom >> newright; rectangle other(rect.top(), rect.left(), newbottom, newright); print_rectangle(std::cout, other); }
C++ ãªãã¦æ¬å½ã«ä¹ ãã¶ãã«è§¦ã£ããªã»ã»ã»