面试题答案
一键面试实现思路
- 定义一个指向
Base
类中print
函数的成员函数指针。 - 在函数中,根据传入指针的类型(通过
dynamic_cast
判断是否能成功转换为Derived*
),来决定是否需要进行派生类特定的处理。 - 使用成员函数指针调用
print
函数。
代码实现
#include <iostream>
#include <typeinfo>
class Base {
public:
virtual void print() {
std::cout << "Base::print()" << std::endl;
}
};
class Derived : public Base {
public:
void print() override {
std::cout << "Derived::print()" << std::endl;
}
};
void callPrint(Base* obj) {
void (Base::*printPtr)() = &Base::print;
if (Derived* derivedObj = dynamic_cast<Derived*>(obj)) {
// 如果是Derived类型,直接调用Derived的print函数
(derivedObj->*printPtr)();
} else {
// 如果是Base类型,调用Base的print函数
(obj->*printPtr)();
}
}
可以通过以下方式测试该函数:
int main() {
Base baseObj;
Derived derivedObj;
callPrint(&baseObj);
callPrint(&derivedObj);
return 0;
}
在上述代码中:
Base
类定义了虚函数print
。Derived
类继承自Base
并覆盖了print
函数。callPrint
函数接受一个Base*
类型的指针,通过dynamic_cast
判断指针指向的对象是否为Derived
类型,如果是,则通过派生类对象调用print
函数,否则通过基类对象调用。- 在
main
函数中,分别创建Base
和Derived
对象,并调用callPrint
函数进行测试。