14:継承と派生クラス

はじめに

C++では「既存のクラスを元に、少し機能を変えた新しいクラスを作る」ことができます。 これを「継承(けいしょう)」と呼びます。


継承の基本

基本の書き方は以下のとおりです:

class 子クラス名 : public 親クラス名 {
    // 追加のメンバやメソッドを定義
};

例:ゲーム内キャラクターの継承

// 14_enemy_inheritance.cpp
#include <iostream>
using namespace std;

class GameObject {
public:
    string name;

    void showName() {
        cout << "オブジェクト名: " << name << endl;
    }
};

class Enemy : public GameObject {
public:
    int hp;

    void attack() {
        cout << name << " が攻撃してきた!" << endl;
    }
};

int main() {
    Enemy slime;
    slime.name = "スライム";
    slime.hp = 30;

    slime.showName();   // 親クラスのメソッド
    slime.attack();     // 子クラス独自のメソッド

    return 0;
}

理解度チェック

問題1(14_check_monster.cpp)

次のコードを実行したとき、出力される内容を答えなさい。

#include <iostream>
using namespace std;

class GameObject {
public:
    string name;

    void show() {
        cout << "名前:" << name << endl;
    }
};

class Boss : public GameObject {
public:
    void taunt() {
        cout << name << "「我を倒せる者などおらぬ!」" << endl;
    }
};

int main() {
    Boss b;
    b.name = "魔王";
    b.show();
    b.taunt();
    return 0;
}
正解・解説を見る
名前:魔王
魔王「我を倒せる者などおらぬ!」

演習問題(14_battle_enemy.cpp)

以下の要件を満たす Enemy クラスを GameObject を継承して作成しなさい。

  1. GameObject クラスには name を持たせ、名前を表示する show() を定義する
  2. Enemy クラスには hpattack() を追加する
  3. attack() は「◯◯が攻撃した!」と表示する
  4. main() で敵を作り、name, hp を代入し、show()attack() を呼び出す
解答例を見る
// 14_battle_enemy.cpp
#include <iostream>
using namespace std;

class GameObject {
public:
    string name;

    void show() {
        cout << "名前:" << name << endl;
    }
};

class Enemy : public GameObject {
public:
    int hp;

    void attack() {
        cout << name << " が攻撃した!" << endl;
    }
};

int main() {
    Enemy goblin;
    goblin.name = "ゴブリン";
    goblin.hp = 50;

    goblin.show();
    goblin.attack();

    return 0;
}

まとめ