C ++ポリモーフィズム
ポリモーフィズム
ポリモーフィズムとは「多くの形態」を意味し、継承によって相互に関連するクラスが多数ある場合に発生します。
前の章で指定したように、 継承により、別のクラスから属性とメソッドを継承できます。ポリモーフィズム は、これらのメソッドを使用してさまざまなタスクを実行します。これにより、さまざまな方法で単一のアクションを実行できます。
たとえば、Animal
というメソッドを持つという基本クラスについて考えてみますanimalSound()
。動物の派生クラスは、豚、猫、犬、鳥である可能性があります-そして、それらはまた、動物の音の独自の実装を持っています(豚の鳴き声、猫の鳴き声など):
例
// Base class
class Animal {
public:
void
animalSound() {
cout << "The animal makes a sound \n"
;
}
};
// Derived class
class Pig : public Animal {
public:
void
animalSound() {
cout << "The pig says: wee wee \n" ;
}
};
// Derived class
class Dog
: public Animal {
public:
void animalSound()
{
cout << "The dog says: bow wow \n" ;
}
};
継承の章:
から、クラスから継承するためにシンボルを使用することを思い出してください。
Pig
これで、オブジェクトを作成してメソッド
Dog
をオーバーライドできます。animalSound()
例
// Base class
class Animal {
public:
void
animalSound() {
cout << "The animal makes a sound \n"
;
}
};
// Derived class
class Pig : public Animal {
public:
void
animalSound() {
cout << "The pig says: wee wee \n" ;
}
};
// Derived class
class Dog
: public Animal {
public:
void animalSound()
{
cout << "The dog says: bow wow \n" ;
}
};
int main() {
Animal
myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
「継承」と「ポリモーフィズム」を使用する理由と時期
-コードの再利用に役立ちます。新しいクラスを作成するときに、既存のクラスの属性とメソッドを再利用します。