2017年12月26日
《その207》 抽象クラス(5)
抽象クラス
今回のプログラムは、基本的な事項のまとめ的なものです。
図形の形状別に、
長方形クラス Rectangle
円クラス Circle
三角形クラス Triangle
があって、それぞれの基底クラスは 抽象クラス Area です。
プログラムの簡単な説明を、コード中にコメントとして入れました。
// ------------------------------------
#include <sstream>
#include <string>
#include <iostream>
// 面積クラス(抽象クラス) Area
class Area {
public:
// 仮想デストラクタ
virtual ~Area() { }
// 純粋仮想関数(面積を計算する)
virtual double area() const = 0;
// 純粋仮想関数(形状を返す)
virtual std::string shape() const = 0;
// 純粋仮想関数(出力用の文字列を作る)
virtual std::string to_string() const = 0;
};
// 長方形クラス
class Rectangle : public Area {
double width;
double height;
public:
Rectangle(double x, double y)
: width(x), height(y) { }
double area() const {
return width * height;
}
std::string shape() const {
return "長方形";
}
std::string to_string() const {
std::ostringstream os;
os << shape() << "\n横幅 : "
<< width << " 高さ : "
<< height << '\n'
<< "面積 : " << area()
<< '\n';
return os.str();
}
};
// 円クラス
class Circle : public Area {
double radius;
public:
Circle(double x) : radius(x) { }
double area() const {
return radius * radius * 3.14;
}
std::string shape() const {
return "円";
}
std::string to_string() const {
std::ostringstream os;
os << shape() << "\n半径 : "
<< radius << "\n面積 : "
<< area() << '\n';
return os.str();
}
};
// 三角形クラス
class Triangle : public Area {
double base;
double height;
public:
Triangle (double x, double y)
: base(x), height(y) { }
double area() const {
return base * height / 2;
}
std::string shape() const {
return "三角形";
}
std::string to_string() const {
std::ostringstream os;
os << shape() << "\n底辺 : "
<< base << " 高さ : "
<< height << '\n'
<< "面積 : " << area()
<< '\n';
return os.str();
}
};
// 挿入子「 << 」の多重定義
// ※挿入子多重定義用関数 operator<<
// の第1引数を ostream& にする必要
// があるため、Areaクラスのメンバ関
// 数として定義することができません。
// ※この operator<<関数を、ヘッダ内に
// 置く場合には、inline を付けて内部
// 結合を与える必要があります。
std::ostream& operator<<(
std::ostream& os,
const Area& a
)
{
return os << a.to_string();
}
// main関数
int main() {
// Area* を使ってすべての派生クラスを指
// すことが可能です。
Area* a[] = {
new Rectangle(12.3, 2.0),
new Circle(2.0),
new Circle(5.0),
new Triangle(5, 3),
};
for (int i = 0; i < 4; i++) {
std::cout << *a[i] << '\n';
delete a[i];
}
}
// ------------------------------------

この記事へのコメント
コメントを書く
この記事へのトラックバックURL
https://fanblogs.jp/tb/7131623
※ブログオーナーが承認したトラックバックのみ表示されます。
この記事へのトラックバック