おまけ
より良いコードとして紹介されてたコードを標準ライブラリの範囲内で書き直してみた。全く同じプログラムじゃないけど、どうせサンプルなんだし細かい動作はどうでもいいでしょ。
// 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++ なんて本当に久しぶりに触ったな・・・