[英]function call inside polymorphic call. virtual function call
The following is calling Derived::fn2()
from Derived::fn1()
, where as fn2()
is not virtual so it should call Base class's function. Could anyone explain why?以下是从
Derived::fn1()
调用Derived::fn2()
) ,其中fn2()
不是虚拟的,因此它应该调用基类的 function。谁能解释为什么?
#include <iostream>
using namespace std;
class Base{
public:
virtual void fn1()
{
cout<<"Base function 1"<<endl;
this->fn2();
}
void fn2()
{
cout<<"Base function 2"<<endl;
}
};
class Derived : public Base{
public:
void fn1()
{
cout<<"Derived function 1 "<<endl;
this->fn2();
}
void fn2()
{
cout<<"Derived function 2"<<endl;
}
};
int main()
{
Base *b = new Derived();
b->fn1();
}
fn2()
is not virtual so it should call Base class's function.fn2()
不是虚拟的,所以它应该调用基类的 function。
No, it shouldn't.不,不应该。 Here you are why:
原因如下:
Derived d;
static_cast<Base&>(d).fn1();
// Calls Derived::fn1 through dynamic dispatching. In Derived::fn1, `this` is
// of type Derived*, so it will call Derived::fn2
// Output:
// Derived function 1
// Derived function 2
static_cast<Base&>(d).fn2();
// fn2() is not virtual, so you overloaded it. You're calling Base::fn2().
// Output:
// Base function 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.