Menu
Coddy logo textTech

ポリモーフィズムの利用

CoddyのCジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 47/61。

challenge icon

チャレンジ

簡単

基底の Shape* ポインターを介して、Circle または Rectangle であるかにかかわらず、any shape を処理できる function を記述して、polymorphism が実際に機能することを証明しましょう。

既存の Circle と Rectangle の実装を基に、強力な抽象化を追加します。それは、any shape type を一様に扱える単一の function です。

プロジェクトには次のファイルが含まれます。

  • shape.h: DrawFuncAreaFunc types を持つ基底の Shape interface。
  • circle.hcircle.c: 前のレッスンで作成した Circle の実装。
  • rectangle.hrectangle.c: 前のレッスンで作成した Rectangle の実装。
  • shape.c: Shape* pointer を受け取る process_shape という新しい function を Implement します。この function は shape の draw function を call し、次にその area function を call して、結果を小数点以下 2 桁で Area: X.XX の format で print します。
  • main.c: polymorphism の動作を実証します。shape type indicator(circle を表す c、rectangle を表す r)を、必要な dimensions とともに read します。適切な shape を create し、その埋め込まれた Shape member への pointer を process_shape に渡します。同じ function が両方の types を処理します。

プログラムは次のいずれかを受け取ります。

  • radius value の後に続く c、または
  • width と height values の後に続く r

入力が c5.0 の場合の出力例:

Drawing Circle with radius: 5.00
Area: 78.54

入力が r4.03.0 の場合の出力例:

Drawing Rectangle with width: 4.00 and height: 3.00
Area: 12.00

ここでの magic は、process_shape が Circle と Rectangle のどちらを処理しているのかをまったく把握していないことです。把握しているのは Shape interface だけです。具体的な shape の埋め込まれた Shape member を Shape* に cast することで、any shape type をこの単一の function に渡せます。これが polymorphism です。つまり、actual object type に基づいて複数の behaviors を持つ 1 つの function です。

main.c から call できるように、shape.hprocess_shape を Declare することを忘れないでください。

自分で試してみよう

#include <stdio.h>
#include "shape.h"
#include "circle.h"
#include "rectangle.h"

int main() {
    // TODO: 図形の種類を表す文字を読み取る('c' は円、'r' は矩形)
    // TODO: 'c' の場合、半径を読み取り、Circle を作成し、その base で process_shape を呼び出す
    // TODO: 'r' の場合、幅と高さを読み取り、Rectangle を作成し、その base で process_shape を呼び出す
    return 0;
}

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: Cオンラインコンパイラ