【发布时间】:2019-06-09 11:39:33
【问题描述】:
我在一次采访中被问到这个问题。我的答案是(3 和 3.6)(错误)。 请解释我的理解是错误的
我的想法是指针bd会指向派生类vtable的_vptr。
Derived 类的 Vtable 将包含 2 个函数
double func(double) // ----->points to Derived::func()
int func(int) // ----->points to Base::func()
因此,
bd->func(2) // will call Base::func() i.e int func(int)
bd->func(2.3) // will call Derived::func() i.e double func(double)
请解释我的理解是错误的。
另外,解释Base::func() 不是virtual 的情况。
在那种情况下,就不会有vtable了吧?如何解决函数调用?
#include <iostream>
using namespace std;
class Base
{
private:
/* data */
public:
Base(/* args */){};
~Base(){};
//int func(int i) getting same answer regardless of virtual
virtual int func(int i)
{
cout << "Base func()" << endl;
return i+1;
}
};
class Derived : public Base
{
public:
Derived(/* args */){};
~Derived(){};
double func(double d)
{
cout << "Derived func()" << endl;
return d+1.3;
}
};
int main() {
Base* bd = new Derived();
cout << bd->func(2) << endl;
cout << bd->func(2.3) << endl;
return 0;
}
预期输出:
Base func()
3
Derived func()
3.6
Actual output:
Base func()
3
Base func()
3
【问题讨论】:
标签: c++ class inheritance virtual-functions