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;
}
自己动手试一试 »
为什么要使用“继承”和“多态性”?以及何时使用?
- 这对于代码重用很有用:当您创建新类时,可以重用现有类的属性和方法。