'override'关键字只是检查重写的虚方法吗?
据我了解,在C ++ 11中引入覆盖
关键字只不过是检查以确保正在实现的函数是覆盖
基类中的虚拟
函数。
As far as I understand, the introduction of override
keyword in C++11 is nothing more than a check to make sure that the function being implemented is the override
ing of a virtual
function in the base class.
是吗?
这确实是个主意。关键是你明确你的意思,以便可以诊断出一个无声的错误:
That's indeed the idea. The point is that you are explicit about what you mean, so that an otherwise silent error can be diagnosed:
struct Base
{
virtual int foo() const;
};
struct Derived : Base
{
virtual int foo() // whoops!
{
// ...
}
};
上面的代码编译,但不是你的意思(注意缺少的常量
)。如果你说, virtual int foo()override
,那么你会得到一个编译器错误,你的函数实际上并没有覆盖任何东西。
The above code compiles, but is not what you may have meant (note the missing const
). If you said instead, virtual int foo() override
, then you would get a compiler error that your function is not in fact overriding anything.