多态是面向对象编程中的一个概念,指的是同一类型的对象在不同的情况下表现出不同的行为。具体地说,多态是通过继承和虚函数来实现的。
在C++中,当一个成员函数被声明为虚函数时,它就可以被子类重写,即在子类中定义与父类相同的函数名、参数列表和返回类型的函数,然后在子类对象上调用该函数时,会根据实际对象类型的不同而调用不同的函数。
举个例子,假设有一个基类Animal,它有一个虚函数makeSound(),它的两个子类Cat和Dog都重写了这个函数。当我们定义一个Animal指针指向Cat或Dog的对象时,调用makeSound()函数时,会根据实际对象类型的不同而调用不同的函数。
class Animal {
public:
virtual void makeSound() {
cout << "Animal is making a sound." << endl;
}
};
class Cat : public Animal {
public:
void makeSound() {
cout << "Meow!" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() {
cout << "Woof!" << endl;
}
};
int main() {
Animal* animal1 = new Cat();
animal1->makeSound(); // 输出 Meow!
Animal* animal2 = new Dog();
animal2->makeSound(); // 输出 Woof!
return 0;
}
上述代码中,animal1指向一个Cat对象,animal2指向一个Dog对象,但在调用makeSound()函数时,它们分别输出了不同的结果,这就是多态的表现。