クラスのメンバに他のクラスのオブジェクトを持つことができました。これをコンポジションといいましたね。 これは第14章でやりました。
ここでは、すぐに例題を考えてみましょう。
前章ではAnimalクラスを考えました。
このAnimalクラスから継承するのではなく、Animalクラスのオブジェクトをメンバに持つCatクラスを作ります。
Animalクラスはコンストラクタで足の数、尾の数を尋ねてnLeg, nTailメンバに格納していました。
Catクラスのコンストラクタでは毛の色を尋ねてcolorメンバに格納します。
Catクラスは次のような感じになります。
class Cat {
char color[16];
Animal pet;
public:
Cat();
int show();
};
メンバにAnimalクラスのpetオブジェクトが含まれています。さて、このshowメンバ関数はAnimalクラスのshowメンバ関数の働きに加えて 毛の色も表示したいとします。
これは、
int Cat::show()
{
pet.show();
cout << "毛の色--" << color << endl;
return 0;
}
のように記述できます。petオブジェクトのshowメンバ関数を実行した後、さらに毛の色を表示すればよいですね。
では、全体のプログラムを見てみましょう。
// cl03.cpp
#include <iostream>
using namespace std;
class Animal {
int nLeg;
int nTail;
public:
Animal();
int show();
};
Animal::Animal()
{
cout << "足の本数--";
cin >> nLeg;
cout << "尾の数--";
cin >> nTail;
}
int Animal::show()
{
char szBuf[32];
if (nTail == 1)
strcpy(szBuf, "尾があります");
else
strcpy(szBuf, "尾はありません");
cout << "足の数は" << nLeg << "本です" << endl;
cout << szBuf << endl;
return 0;
}
class Cat {
char color[16];
Animal pet;
public:
Cat();
int show();
};
Cat::Cat()
{
cout << "毛の色--";
cin >> color;
}
int Cat::show()
{
pet.show();
cout << "毛の色--" << color << endl;
return 0;
}
int main()
{
Cat Mike;
Mike.show();
return 0;
}
main関数では、CatクラスのMikeオブジェクトを宣言してshowメンバ関数を呼んでいるだけです。
Update Oct/14/2003 By Y.Kumei