覆盖方法时 virtual 关键字是什么意思? [英] What does the virtual keyword mean when overriding a method?
问题描述
关键字 virtual 在覆盖方法时有什么作用?我没有使用它,一切正常.
What does the keyword virtual do when overriding a method? I'm not using it and everything works fine.
每个编译器在这方面的行为都一样吗?
Does every compiler behave the same in this regard?
我应该使用它还是不使用它?
Should I use it or not?
推荐答案
没有它你不能重写成员函数.
You cannot override a member function without it.
您只能隐藏一个.
struct Base {
void foo() {}
};
struct Derived : Base {
void foo() {}
};
Derived::foo
不会覆盖Base::foo
;它只是隐藏它,因为它具有相同的名称,例如:
Derived::foo
does not override Base::foo
; it simply hides it because it has the same name, such that the following:
Derived d;
d.foo();
调用Derived::foo
.
virtual
启用多态性,以便您实际上覆盖函数:
struct Base {
virtual void foo() {}
};
struct Derived : Base {
virtual void foo() {} // * second `virtual` is optional, but clearest
};
Derived d;
Base& b = d;
b.foo();
这会调用Derived::foo
,因为它现在覆盖 Base::foo
—你的对象是多态的.
This invokes Derived::foo
, because this now overrides Base::foo
— your object is polymorphic.
(您还必须为此使用引用或指针,因为切片问题.)
(You also have to use references or pointers for this, due to the slicing problem.)
Derived::foo
不需要重复virtual
关键字,因为Base::foo
已经使用了它.这是由标准保证的,您可以信赖它.但是,有些人认为为了清楚起见最好将其保留.
Derived::foo
doesn't need to repeat thevirtual
keyword becauseBase::foo
has already used it. This is guaranteed by the standard, and you can rely on it. However, some think it best to keep that in for clarity.
这篇关于覆盖方法时 virtual 关键字是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!