面试题答案
一键面试- 方法:
- 在基类中将
printInfo
函数声明为虚函数。这样在派生类中可以通过override
关键字来重写该函数,在重写的函数中可以先调用基类的printInfo
函数,然后再添加派生类特有的打印逻辑,从而实现代码复用。
- 在基类中将
- 代码示例:
#include <iostream>
class Base {
public:
virtual void printInfo() {
std::cout << "This is basic information from base class." << std::endl;
}
};
class Derived : public Base {
public:
void printInfo() override {
Base::printInfo();
std::cout << "This is additional information from derived class." << std::endl;
}
};
你可以使用以下方式测试这个代码:
int main() {
Base* basePtr = new Derived();
basePtr->printInfo();
delete basePtr;
return 0;
}
在上述代码中,Base
类的 printInfo
函数是虚函数,Derived
类重写了 printInfo
函数。在 Derived
类的 printInfo
函数中,先调用了基类的 printInfo
函数,然后输出了派生类特有的信息,实现了代码复用。在 main
函数中,通过基类指针调用 printInfo
函数,实际调用的是派生类重写后的 printInfo
函数。