面试题答案
一键面试-
C++实现多态的三个必要条件:
- 继承:派生类从基类继承,形成类的层次结构。
- 虚函数:在基类中使用
virtual
关键字声明虚函数,派生类重写这些虚函数。 - 通过基类指针或引用调用虚函数:这样在运行时根据指针或引用实际指向的对象类型来决定调用哪个类的虚函数。
-
示例代码:
#include <iostream>
class Base {
public:
virtual void display() {
std::cout << "This is Base class." << std::endl;
}
};
class Derived : public Base {
public:
void display() override {
std::cout << "This is Derived class." << std::endl;
}
};
int main() {
Base* basePtr;
Base baseObj;
Derived derivedObj;
basePtr = &baseObj;
basePtr->display();
basePtr = &derivedObj;
basePtr->display();
return 0;
}
- 多态体现解释:
- 在
main
函数中,首先定义了一个Base
类型的指针basePtr
。 - 当
basePtr
指向baseObj
对象时,调用basePtr->display()
,由于display
是虚函数,此时调用的是Base
类的display
函数,输出This is Base class.
。 - 当
basePtr
重新指向derivedObj
对象时,再次调用basePtr->display()
,虽然basePtr
的类型是Base*
,但由于display
是虚函数,运行时会根据basePtr
实际指向的Derived
类对象,调用Derived
类的display
函数,输出This is Derived class.
。这就体现了多态性,即在运行时根据对象的实际类型来决定调用哪个类的虚函数,而不是根据指针或引用的静态类型。
- 在