问题描述
当一个方法在类中声明为 virtual
时,它在派生类中的覆盖自动被视为 virtual
在这种情况下,C ++语言使此关键字 virtual
可选:
When a method is declared as virtual
in a class, its overrides in derived classes are automatically considered virtual
as well, and the C++ language makes this keyword virtual
optional in this case:
class Base {
virtual void f();
};
class Derived : public Base {
void f(); // 'virtual' is optional but implied.
};
我的问题是: virtual
可选?
我知道编译器不是绝对必要的,但我认为开发人员将受益,如果这样的约束被强制
I know that it is not absolutely necessary for the compiler to be told that, but I would think that developers would benefit if such a constraint was enforced by the compiler.
例如,当我阅读别人的代码时我不知道一个方法是否是虚拟的,我必须跟踪它的超类来确定。而一些编码标准()使其成为必须将 virtual
关键字放在所有子类中。
E.g., sometimes when I read others' code I wonder if a method is virtual and I have to track down its superclasses to determine that. And some coding standards (Google) make it a 'must' to put the virtual
keyword in all subclasses.
推荐答案
真的更好,使编译器强制执行虚拟在这种情况下,我同意这是一个错误设计,为维持向后兼容性。
Yeah, it would really be nicer to make the compiler enforce the virtual in this case, and I agree that this is a error in design that is maintained for backwards compatibility.
但是有一个技巧这将是不可能没有它:
However there's one trick that would be impossible without it:
class NonVirtualBase {
void func() {};
};
class VirtualBase {
virtual void func() = 0;
};
template<typename VirtualChoice>
class CompileTimeVirtualityChoice : public VirtualChoice {
void func() {}
};
我们有编译时选择,我们想要func的虚拟化:
With the above we have compile time choice wether we want virtuality of func or not:
CompileTimeVirtualityChoice<VirtualBase> -- func is virtual
CompileTimeVirtualityChoice<NonVirtualBase> -- func is not virtual
...但同意,这是一个次要的好处,一个函数的虚拟性和我自己,我总是试图在适当的地方类型虚拟。
... but agreed, it's a minor benefit for the cost of seeking a function's virtuality, and myself, I always try to type virtual everywhere where applicable.
这篇关于为什么'virtual'对于派生类中的重写方法是可选的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!