C++ 多型
多型
多型性意為“多種形式”,它發生在我們有許多透過繼承相互關聯的類時。
正如我們在上一章中指定的; 繼承 允許我們從另一個類繼承屬性和方法。多型使用這些方法來執行不同的任務。這使我們能夠以不同的方式執行單個操作。
例如,考慮一個名為 Animal
的基類,它有一個名為 animalSound()
的方法。Animal 的派生類可以是豬、貓、狗、鳥——它們也有自己對動物聲音的實現(豬哼哼,貓喵喵叫,等等)。
示例
// 基類
class Animal {
public
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// 派生類
class Pig : public Animal {
public
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// 派生類
class Dog : public Animal {
public
void animalSound() {
cout << "The dog says: bow wow \n";
}
};
還記得在 繼承章節 中,我們使用 :
符號來繼承一個類。
現在我們可以建立 Pig
和 Dog
物件並重寫 animalSound()
方法。
示例
// 基類
class Animal {
public
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// 派生類
class Pig : public Animal {
public
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// 派生類
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;
}
自己動手試一試 »
為什麼要使用“繼承”和“多型性”?以及何時使用?
- 這對於程式碼重用很有用:當您建立新類時,可以重用現有類的屬性和方法。