とくにあぶなくないRiSKのブログ

危ないRiSKのブログだったかもしれない。本当はRiSKだけどググラビリティとか取得できるIDの都合でsscriskも使ったり。

STLとオブジェクト指向プログラミングの結合 shape.hpp

STL―標準テンプレートライブラリによるC++プログラミング 第2版
ex17-01.cpp, shape.hpp, screen.hpp の三つのファイルを用いたプログラム。

// shape.hpp

#include"screen.hpp"

inline int max(int a, int b)
{
 return a > b ? a : b;
}

inline int min(int a, int b)
{
 return a < b ? a : b;
}

struct shape
{
 static shape* list;
 shape* next;
 shape()
  : next(list)
 {
  list = this;
 }
 virtual point north()const = 0;
 virtual point south()const = 0;
 virtual point east() const = 0;
 virtual point west() const = 0;
 virtual point neast()const = 0;
 virtual point seast()const = 0;
 virtual point nwest()const = 0;
 virtual point swest()const = 0;
 virtual void draw() = 0;
 virtual void move(int, int) = 0;
};
shape* shape::list = 0;

class line
 : public shape
{
 point w, e;
public:
 line(point a, point b)
  : w(a), e(b)
 {}
 line(point a, int len)
  : w(point(a.x + len - 1, a.y)), e(a)
 {}
 virtual point north()const
 {
  return point((w.x + e.x) / 2, max(w.y, e.y));
 }
 virtual point south()const
 {
  return point((w.x + e.x) / 2, min(w.y, e.y));
 }
 virtual point east()const
 {
  return point(max(w.x, e.x), (w.y + e.y) / 2);
 }
 virtual point west()const
 {
  return point(min(w.x, e.x), (w.y + e.y) / 2);
 }
 virtual point neast()const
 {
  return point(max(w.x, e.x), max(w.y, e.y));
 }
 virtual point seast()const
 {
  return point(max(w.x, e.x), min(w.y, e.y));
 }
 virtual point nwest()const
 {
  return point(min(w.x, e.x), max(w.y, e.y));
 }
 virtual point swest()const
 {
  return point(min(w.x, e.x), min(w.y, e.y));
 }
 virtual void draw()
 {
  put_line(w, e);
 }
 virtual void move(int a, int b)
 {
  w.x += a;
  w.y += b;
  e.x += a;
  e.y += b;
 }
};

class rectangle
 : public shape
{
 point sw, ne;
public:
 rectangle(point a, point b)
  : sw(point(min(a.x, b.x), min(a.y, b.y))),
    ne(point(max(a.x, b.x), max(a.y, b.y)))
 {}
 virtual point north()const
 {
  return point((sw.x + ne.x) / 2, ne.y);
 }
 virtual point south()const
 {
  return point((sw.x + ne.x) / 2, sw.y);
 }
 virtual point east() const
 {
  return point(ne.x, (sw.y + ne.y) / 2);
 }
 virtual point west() const
 {
  return point(sw.x, (sw.y + ne.y) / 2);
 }
 virtual point neast()const
 {
  return ne;
 }
 virtual point seast()const
 {
  return point(ne.x, sw.y);
 }
 virtual point nwest()const
 {
  return point(sw.x, ne.y);
 }
 virtual point swest()const
 {
  return sw;
 }
 virtual void draw()
 {
  point nw(sw.x, ne.y);
  point se(ne.x, sw.y);
  put_line(nw, ne);
  put_line(ne, se);
  put_line(se, sw);
  put_line(sw, nw);
 }
 virtual void move(int a, int b)
 {
  sw.x += a;
  sw.y += b;
  ne.x += a;
  ne.y += b;
 }
};

void shape_refresh()
{
 screen_clear();
 for(shape* p = shape::list; p; p = p->next)
  p->draw();
 screen_refresh();
 system("pause");
}
void stack(shape* p, const shape* q)
{
 point n = q->north();
 point s = p->south();
 p->move(n.x - s.x, n.y - s.y + 1);
}