面试题答案
一键面试- 对代码扩展性的具体影响:
- 多态性支持:允许在运行时根据对象的实际类型来决定调用哪个函数版本,而不是在编译时就确定。这使得代码可以更加灵活地处理不同类型的对象,提高了代码的可扩展性。例如,在一个图形绘制系统中,可以有一个父类
Shape
,子类Circle
、Rectangle
等继承自它。通过虚函数draw
,可以在运行时根据具体的Shape
类型(实际是Circle
或Rectangle
等)来调用对应的draw
函数,而不需要在代码中写大量的条件判断语句。 - 易于代码维护和扩展:当需要添加新的子类时,只需要在子类中重写虚函数,而不需要修改调用该函数的现有代码。比如在上述图形绘制系统中,如果要添加一个新的
Triangle
类,只需要在Triangle
类中重写draw
虚函数,而调用draw
函数的其他代码不需要改变。
- 多态性支持:允许在运行时根据对象的实际类型来决定调用哪个函数版本,而不是在编译时就确定。这使得代码可以更加灵活地处理不同类型的对象,提高了代码的可扩展性。例如,在一个图形绘制系统中,可以有一个父类
- 示例代码:
#include <iostream>
// 父类
class Animal {
public:
// 虚函数
virtual void makeSound() {
std::cout << "Animal makes a sound" << std::endl;
}
};
// 子类1
class Dog : public Animal {
public:
void makeSound() override {
std::cout << "Dog barks" << std::endl;
}
};
// 子类2
class Cat : public Animal {
public:
void makeSound() override {
std::cout << "Cat meows" << std::endl;
}
};
// 函数接受一个Animal指针并调用makeSound函数
void hearSound(Animal* animal) {
animal->makeSound();
}
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
hearSound(animal1);
hearSound(animal2);
delete animal1;
delete animal2;
return 0;
}
在上述代码中:
Animal
类中的makeSound
函数被声明为虚函数。Dog
和Cat
类继承自Animal
类,并各自重写了makeSound
函数。hearSound
函数接受一个Animal
指针,并调用makeSound
函数。在main
函数中,分别创建了Dog
和Cat
对象,并通过Animal
指针传递给hearSound
函数,运行时会根据对象的实际类型(Dog
或Cat
)调用相应的makeSound
函数版本,体现了虚函数带来的多态性,使得代码具有更好的扩展性。