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;
}次のコードを実行したとき、出力される内容を答えなさい。
#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;
}名前:魔王
魔王「我を倒せる者などおらぬ!」
以下の要件を満たす Enemy クラスを
GameObject を継承して作成しなさい。
GameObject クラスには name
を持たせ、名前を表示する show() を定義するEnemy クラスには hp と
attack() を追加するattack() は「◯◯が攻撃した!」と表示する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;
}class B : public A
とすると、BはAを継承したクラスになります。