C++ 多态性(Polymorphism)
多态性
多态性意味着“多种形式”,它出现在我们通过继承相互关联的多个类中。
就像我们在上一章中指定的那样;继承允许我们从另一个类继承属性和方法。多态性使用这些方法来执行不同的任务。这使我们能够以不同的方式执行单个操作。
例如,考虑一个名为 Animal 的基类,它有一个名为 AnimalSound() 的方法。动物的派生类可以是猪、猫、狗、鸟 - 并且它们也有自己的动物声音实现(猪叫声和猫喵叫声等):
实例
// 基类
class Animal {
public:
void animalSound() {
cout << "动物发出声音 \n";
}
};
// 派生类
class Pig : public Animal {
public:
void animalSound() {
cout << "猪说:wee wee \n";
}
};
// 派生类
class Dog : public Animal {
public:
void animalSound() {
cout << "狗说:bow wow \n";
}
};
从继承章节中我们记得,我们使用 : 符号从类继承。
现在我们可以创建 Pig 和 Dog 对象,并重写 AnimalSound() 方法:
实例
// 基类
class Animal {
public:
void animalSound() {
cout << "动物发出声音 \n";
}
};
// 派生类
class Pig : public Animal {
public:
void animalSound() {
cout << "猪说:wee wee \n";
}
};
// 派生类
class Dog : public Animal {
public:
void animalSound() {
cout << "狗说:bow wow \n";
}
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
为什么以及何时使用“继承”和“多态”?
- 它对于代码可重用性很有用:创建新类时重用现有类的属性和方法。