C++ 中的函数覆盖在没有“虚拟"的情况下工作 [英] Function overriding in C++ works without 'virtual'
问题描述
我有一个包含一些函数的类(没有一个是虚拟的),另外还有 2 个类公开继承了该类.在两个子类中,我都覆盖了基类的相同功能.
I have a class that contains some functions (none are virtual) and 2 more classes publicly inherit that class. In both the sub classes I override the same function of the base class.
在 main(位于同一文件)中创建所有三个类的对象后,我使用基类对象调用原始函数,并使用派生类对象调用覆盖函数.
After creating objects of all three classes in main (located at the same file), I call the original function with the baseclass object and the overridden functions with the derivedclass objects.
我期望所有 3 个函数调用都运行来自基类的原始函数(因为我没有在代码中的任何地方使用虚拟"),但我实际上让该函数的每个版本都根据类中的类工作它被定义(3个不同的版本).
I was expecting all 3 function calls to run the original function from the base class (since I didn't use 'virtual' anywhere in the code), but I actually get each version of that function working according to the class in which it was defined (3 different versions).
我有 Base & 类推导如下:
I have the classes Base & Derived as follows:
struct Base
{
void foo();
};
struct Derived : Base
{
void foo();
};
主要内容:
int main()
{
Derived d;
d.foo();
}
如果不使用虚拟",我认为 d.foo() 应该运行 Base::foo().
I thought d.foo() should run Base::foo() if not using 'virtual'.
推荐答案
这不是压倒一切"……而且也没有必要.
This is not "overriding"... and it doesn't need to be.
struct Base
{
void foo();
};
struct Derived : Base
{
void foo();
};
int main()
{
Derived d;
d.foo();
}
如果我理解正确,那么您期望它执行 Base::foo()
,因为函数不是虚拟的,因此一个不会覆盖另一个.
If I understand you correctly, then you were expecting this to execute Base::foo()
, because the functions are not virtual and therefore one does not override the other.
但是,在这里,您不需要虚拟分派:继承规则只是声明您将获得运行它的对象类型的正确函数.
But, here, you do not need virtual dispatch: the rules of inheritance simply state that you'll get the right function for the type of the object you run it on.
当您需要虚拟分派/覆盖时,情况略有不同:当您使用间接时:
When you need virtual dispatch/overriding is a slightly different case: it's when you use indirection:
int main()
{
Base* ptr = new Derived();
ptr->foo();
delete ptr;
}
在上面的代码片段中,结果将是 Base::foo()
被调用,因为表达式 ptr->foo()
不知道*ptr
是真的一个Derived
.它只知道 ptr
是一个 Base*
.
In the above snippet, the result will be that Base::foo()
is called, because the expression ptr->foo()
doesn't know that *ptr
is really a Derived
. All it knows is that ptr
is a Base*
.
这就是添加virtual
(并在这样做时使一个函数覆盖另一个函数)产生奇迹的地方.
This is where adding virtual
(and, in doing so, making the one function override the other) makes magic happen.
这篇关于C++ 中的函数覆盖在没有“虚拟"的情况下工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!