C++ Polymorphism
ความหลากหลาย
Polymorphism หมายถึง "หลายรูปแบบ" และเกิดขึ้นเมื่อเรามีหลายชั้นเรียนที่เกี่ยวข้องกันโดยการสืบทอด
เช่นเดียวกับที่เราระบุไว้ในบทที่แล้ว การ สืบทอดทำให้เราสืบทอดแอตทริบิวต์และเมธอดจากคลาสอื่น ความ หลากหลาย ใช้วิธีการเหล่านั้นเพื่อทำงานที่แตกต่างกัน ซึ่งช่วยให้เราดำเนินการสิ่งเดียวได้หลายวิธี
ตัวอย่างเช่น ลองนึกถึงคลาสฐานที่เรียกAnimal
ว่าซึ่งมีเมธอดที่เรียกว่าanimalSound()
. คลาสที่ได้รับมาจากสัตว์ ได้แก่ หมู แมว สุนัข นก และพวกมันยังมีการใช้เสียงสัตว์เป็นของตัวเอง (หมู oinks และ meows แมว ฯลฯ):
ตัวอย่าง
// 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;
}
ทำไมและเมื่อใดจึงควรใช้ "การสืบทอด" และ "ความหลากหลาย"?
- มีประโยชน์สำหรับการนำโค้ดกลับมาใช้ใหม่: ใช้แอตทริบิวต์และวิธีการของคลาสที่มีอยู่ซ้ำเมื่อคุณสร้างคลาสใหม่