覆盖非虚拟方法 [英] Overriding non-virtual methods
问题描述
让我们在Visual C ++ 2010中假定这种情况:
Let's assume this scenario in Visual C++ 2010:
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
public:
int b;
void Display()
{
cout<<"Base: Non-virtual display."<<endl;
};
virtual void vDisplay()
{
cout<<"Base: Virtual display."<<endl;
};
};
class Derived : public Base
{
public:
int d;
void Display()
{
cout<<"Derived: Non-virtual display."<<endl;
};
virtual void vDisplay()
{
cout<<"Derived: Virtual display."<<endl;
};
};
int main()
{
Base ba;
Derived de;
ba.Display();
ba.vDisplay();
de.Display();
de.vDisplay();
_getch();
return 0;
};
从理论上讲,这个小应用程序的输出应为:
Theoretically, the output of this little application should be:
- 基本:非虚拟显示.
- 基本:虚拟显示.
- 基础:非虚拟展示.
- 派生:虚拟显示.
因为基类的Display方法不是虚拟方法,所以派生类不应覆盖它.对吧?
because the Display method of the Base class is not a virtual method so the Derived class should not be able to override it. Right?
问题在于,当我运行该应用程序时,它会打印以下内容:
The problem is that when I run the application, it prints this:
- 基本:非虚拟显示.
- 基本:虚拟显示.
- 派生:非虚拟显示.
- 派生:虚拟显示.
所以我不了解虚拟方法的概念,或者在Visual C ++中发生了奇怪的事情.
So either I didn't understand the concept of virtual methods or something strange happens in Visual C++.
有人可以帮我一个解释吗?
Could someone help me with an explanation?
推荐答案
是的,您有点误会了.
在这种情况下,派生类上同名的方法将隐藏父方法.您会想到,如果不是这种情况,尝试创建与基类非虚拟方法同名的方法会引发错误.这是允许的,这不是问题-如果您直接完成该方法就调用该方法,就可以了.
The method of the same name on the derived class will hide the parent method in this case. You would imagine that if this weren't the case, trying to create a method with the same name as a base class non-virtual method should throw an error. It is allowed and it's not a problem - and if you call the method directly as you have done it will be called fine.
但是,由于是非虚拟的,因此不会使用允许多态的C ++方法查找机制.因此,例如,如果您创建了派生类的实例,但通过指向基类的指针调用了"Display"方法,则将调用基类的方法,而对于"vDisplay",则将调用派生方法.
But, being non-virtual, C++ method lookup mechanisms that allow for polymorphism won't be used. So for example if you created an instance of your derived class but called your 'Display' method via a pointer to the base class, the base's method will be called, whereas for 'vDisplay' the derived method would be called.
例如,尝试添加以下行:
For example, try adding these lines:
Base *b = &ba;
b->Display();
b->vDisplay();
b = &de;
b->Display();
b->vDisplay();
...并按预期观察输出:
...and observe the output as expected:
基本:非虚拟显示.
基础:虚拟显示.
基本:非虚拟展示.
派生:虚拟显示.
Base: Non-virtual display.
Base: Virtual display.
Base: Non-virtual display.
Derived: Virtual display.
这篇关于覆盖非虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!