【c++】クラスの基礎と使い方
クラスとはオブジェクトを作成するための仕組みです。
現在使用されているプログラミング言語のほとんどが持っている機能です。
プロジェクトでも使われることがほとんどでサービスを開発するために必須の知識と言えます。
c++でもクラスの機能が用意されています。
今回は「クラスの定義」と「継承」についてまとめたいと思います。
クラス定義
早速定義してみましょう
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream> using namespace std; class Sample { int value; public: Sample() { cout << "Constructor" << endl; value = 10; } ~Sample() { cout << "Destructor" << endl; } int getValue() { return value; } void setValue(int v) { value = v; } }; int main(void) { Sample sample; cout << sample.getValue() << endl; sample.setValue(100); cout << sample.getValue() << endl; } |
このクラスは以下のメンバを持ちます。
- value
- 変数
- privateなため外部から直接操作できない
- sample.value=10 のようなことはできない
- getValue()
- 関数
- valueを取得する
- setValue()
- 関数
- valueに値を設定する
- Sample
- コンストラクタ(関数)
- クラス宣言時に実行される
- Sample sample;
- ~Sample
- デストラクタ
- オブジェクトが破棄されたときに実行される
- スコープから外れたときやプログラムの終了時
- 今回の例で言うとmain関数の終了時
もしvalue変数を外部から直接操作できるようにしたい場合は、「public:」の下に記述します。
このプログラムの実行結果です。
1 2 3 4 |
Constructor 10 100 Destructor |
継承
c++に限らずオブジェクト指向言語のプロジェクトでは汎用的なクラスを定義し、
そのクラスを継承することによって、
それぞれの目的を実現するために特化した機能をもつクラスを作成することが多いです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
#include <iostream> using namespace std; class A { protected: int a_value; public: A() { cout << "A class Constructor" << endl; a_value = 10; } ~A() { cout << "A class Destructor" << endl; } int getValue() { return a_value; } void setValue(int v) { a_value = v; } void printinfo() { cout << "This is Class A" << endl; } }; class B: public A { public: B() { cout << "B class Constructor" << endl; a_value = 1000; } ~B() { cout << "B class Destructor" << endl; } void addAvalue(int num) { a_value += num; } void printinfo() { cout << "This is Class B" << endl; } }; int main(void) { B b; cout << b.getValue() << endl; b.setValue(100); cout << b.getValue() << endl; b.addAvalue(1000); cout << b.getValue() << endl; b.printinfo(); } |
先程のSampleクラスとほぼ同様の定義をもつクラスAを定義し、
クラスAを継承したクラスBを定義しています。
継承する際は新しいクラス名のあとに親クラスを指定します。
1 |
class {新しいクラス}: public {親クラス} |
Sampleクラスにはなかった要素ですが、
クラスAではメンバ変数を「protected:」の下に定義しています。
これは継承先(クラスB)から操作できるようにするためです。
仮にクラスAをprotectedを指定せずに変数を定義し、
かつその変数をクラスBから操作しようとするとコンパイル時にエラーになります。
またクラスAで定義されているprintinfo関数がクラスBで再定義しています。
継承元のクラスのメソッドど同じ名前のメソッドを定義することを「オーバーライド」といいます。
実行結果です。
1 2 3 4 5 6 7 8 |
A class Constructor B class Constructor 1000 100 1100 This is Class B B class Destructor A class Destructor |