C++ 多态性
多态
多态性意味着 "多种形式",当我们有许多通过继承相互关联的类时,就会发生多态。
如前一章所述;继承 允许我们从另一个类继承属性和方法。多态性 使用这些方法来执行不同的任务。这允许我们以不同的方式执行单个操作。
例如,考虑一个名为 Animal
的超类,它有一个名为 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" ;
}
};
请记住,在 继承 一章中,我们使用:
符号从类继承。
现在我们可以创建 Pig
和 Dog
对象,并重写 animalSound()
方法:
实例
#include <iostream>
#include <string>
using namespace std;
// 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;
}
为什么以及何时使用 "继承" 和 "多态"?
- 它对代码的可重用性很有用:在创建新类时重用现有类的属性和方法。