下面是从Derived::fn2()调用Derived::fn1(),因为fn2()不是虚拟的,所以它应该调用基类的函数。有人能解释原因吗?
#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();
}发布于 2022-04-23 21:17:12
fn2()不是虚拟的,所以它应该调用基类的函数。
不,不应该。这就是为什么:
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 2https://stackoverflow.com/questions/71983565
复制相似问题