C++スコーラ

継承

最終更新:

cschola

- view
管理者のみ編集可

クラスの継承


クラスは継承という概念を使い拡張することが可能です。

継承はあるクラスから性質を受け継いで新しいクラスを作ることで
  • 新しいメンバ関数、メンバ変数の追加
  • メソッドの上書き
等が出来ます。

拡張される側のクラスの事を
「基底クラス」
といい
拡張された側のクラスを
「派生クラス」
といいます。

クラスの継承は以下のようなルールがあります。
  • 派生クラスは基底クラスのメンバ変数と関数を受け継ぐ。
  • 基底クラスは1つしか指定できない。
  • 派生クラスは複数作成可能。

このコードでは、「Student」クラスが「Person」クラスを継承しています。

/*--------------Person.hの中身----------------*/
#pragma once
#include < string >


class Person{
public:
	std::string name;	// 名前
	int age;	// 年齢

	Person(std::string name, int age);	// コンストラクタ
	virtual ~Person();		// デストラクタ
};

/*--------------Person.cppの中身----------------*/
#include "Person.h"
using namespace std;
Person::Person(string name, int age){
	this->name = name;
	this->age = age;
}
Person::~Person(){

}

/*--------------Student.hの中身----------------*/
#pragma once
#include "Person.h"

class Student : public Person {
public:
	int id;		//学籍番号

	Student(std::string name, int age, int id);	// コンストラクタ
	~Student(); 	// デストラクタ
};

/*--------------Student.cppの中身----------------*/
#include "Student.h"
using namespace std;

Student::Student(std::string name, int age, int id) : Person(name, age) {
	this->id = id;
}
Student::~Student(){

}

今回は特別にメンバを全てpublic にしています。
これは、privateメンバが派生クラスに継承できないためです。
詳しくは後の章で説明します。

virtual ~Person();	// デストラクタ
上の文は「Person」クラスのデストラクタです。
基底クラスのデストラクタには必ず「virtual」を前に付けてください。
付けないと基底クラスのデストラクタが呼ばれない場合があります。
virtualが何なのかは後の章で説明します。

class Student : public Person{
上の文はで継承関係を表しています。
こう書くことで「Student」クラスは「Person」クラスを継承したことになります。

Student::Student(std::string name, int age, int id) : Person(name, age) {
	this->id = id;
}
派生クラスのコンストラクタでは、基底クラスのコンストラクタを呼ぶことができます。
: Person(name, age) がそれに当たります。
これを書かない場合は、自動で基底クラスのデフォルトコンストラクタが呼ばれます。

継承されたメンバ

派生クラスは基底クラスのprivate以外のメンバを引き継ぎます
つまり、Studentクラスは以下のように作成したのと同じように扱えます。
class Student{
public:
	std::string name;	// 名前
	int age;	// 年齢

	int id;		//学籍番号 

	Student(std::string name, int age, int id);	// コンストラクタ
	~Student(); 	// デストラクタ
}

そのため、以下のようにメンバを参照することができます。
Student* satou = new Student("佐藤", 69, 241035);

cout << 名前: << satou->name << endl;
cout << 年齢: << satou->age << endl;
cout << 学籍番号: << satou->id << endl;

delete satou;

逆に基底クラスを作った場合は派生クラスのメンバにはアクセスできません。
Person* hero = new Person("佐藤", 69);

cout << 名前: << satou->name << endl;
cout << 年齢: << satou->age << endl;
cout << 学籍番号: << satou->id << endl;	//【エラー】

delete satou;

また、派生クラスの関数やコンストラクタ内からでも基底クラスのメンバにアクセスできます
Student::Student(string name, int age, int id) : Person(name, age) {
	this->id = id;
}

	cout << 名前: << satou->name << endl;
	cout << 年齢: << satou->age << endl;
	cout << 学籍番号: << satou->id << endl;

問題

 第1問
以下の二つのクラスの共通メンバを抜き出して基底クラス「Animal」を作りなさい。
また、以下のクラスを「Animal」クラスを継承するように書き換えなさい
class Human{
public:
	string name;	// 名前
	int age;	// 年齢
	int money;	// 金

	Human(string name, int age, int money);
	~Human();
}

class monkey{
public:
	int age;	// 年齢
	int banana;	// ばなな

	monkey(int age, int banana);
	~monkey();
}

testcounter
合計 -
今日 -
昨日 -
目安箱バナー