c++のマルチステート(1つのインタフェース、複数の実装)
5668 ワード
なぜマルチステートを使用するのですか?同じセグメントのコードが異なるオブジェクト呼び出し時に異なる効果をもたらすことを解決するために、コードの冗長性がマルチステートを実現する3つの条件を回避しました:1継承がある2虚関数がある書き換えがある3親ポインタ(親参照)で子オブジェクトを指す...
#include "iostream"
using namespace std;
class animal
{
public:
virtual int eat()
{
return 10;
}
};
class plant
{
public:
int eat()
{
return 25;
}
};
class mouse :public animal// ,
{
public:
virtual int eat()// , ( 2 , , ; )
{
return 20;
}
};
class bird :public animal
{
public:
virtual int eat()
{
return 30;
}
};
void playLand(animal &animal,plant *plant)// , ( ) ....// , ,
{
if (animal.eat() > plant->eat())
{
cout << " " << endl;
}
else
{
cout << " " << endl;
}
}
void main()
{
animal animal1;
mouse mouse1;
bird bird1;
plant flowers;
playLand(animal1, &flowers);
playLand(mouse1, &flowers);
playLand(bird1, &flowers);
}