MST

星途 面试题库

面试题:C++函数重载匹配规则之专家题

考虑以下复杂的C++ 代码结构: ```cpp class Base { public: virtual void func(int a) { std::cout << "Base::func(int)" << std::endl; } }; class Derived : public Base { public: void func(double a) override { std::cout << "Derived::func(double)" << std::endl; } void func(int a, int b) { std::cout << "Derived::func(int, int)" << std::endl; } }; void callFunc(Base& obj, int a) { obj.func(a); } void callFunc(Derived& obj, double a) { obj.func(a); } int main() { Derived d; callFunc(d, 5); callFunc(d, 5.5); return 0; } ``` 1. 分析`callFunc(d, 5);`和`callFunc(d, 5.5);`这两次函数调用的匹配过程,涉及到虚函数、函数重载以及对象类型转换等知识。 2. 如果要在`Derived`类中添加一个`func`函数`void func(int a, double b);`,并保证`callFunc(d, 5, 5.5);`能正确调用该函数,需要对代码做出哪些修改(从函数重载匹配规则的角度考虑)?
38.3万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

1. 函数调用匹配过程分析

  • callFunc(d, 5);
    • 首先,callFunc函数有两个重载版本,void callFunc(Base& obj, int a)void callFunc(Derived& obj, double a)
    • 实参dDerived类型,它可以隐式转换为Base类型,5int类型。第一个版本void callFunc(Base& obj, int a)匹配度更高,因为DerivedBase的转换是标准转换,且int类型匹配。
    • callFunc(Base& obj, int a)函数中,obj.func(a)调用虚函数func。由于obj实际类型是Derived,根据虚函数机制,会调用Derived类中被重写的虚函数。但Derived类中没有重写void func(int a),而是继承自Base类,所以会调用Base::func(int),输出Base::func(int)
  • callFunc(d, 5.5);
    • 对于callFunc函数的重载版本,void callFunc(Base& obj, int a)不匹配,因为5.5double类型,与int不匹配。
    • void callFunc(Derived& obj, double a)匹配,因为dDerived类型,5.5double类型。
    • 然后在这个函数中调用obj.func(a),会调用Derived类中的void func(double a)函数,输出Derived::func(double)

2. 代码修改

  • 要使callFunc(d, 5, 5.5);能正确调用void func(int a, double b);,需要添加一个匹配的callFunc函数重载。
  • 当前callFunc函数没有接受三个参数且符合类型要求的版本。
  • 所以添加如下函数:
void callFunc(Derived& obj, int a, double b) {
    obj.func(a, b);
}

这样从函数重载匹配规则角度,当调用callFunc(d, 5, 5.5);时,就会调用这个新添加的callFunc函数,进而调用Derived类中的void func(int a, double b);函数。