功能呼叫在多态性调用中。虚拟功能调用
以下是调用derived :: fn2()
来自derived :: fn1()
,其中AS 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();
}
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?
#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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,不应该。这就是为什么:
No, it shouldn't. Here you are why: