显式覆盖和最终c ++ 0x [英] Explicit overrides and final c++0x

查看:191
本文介绍了显式覆盖和最终c ++ 0x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据维基百科,在此示例中:

struct Base {
    virtual void some_func(float);
};

struct Derived : Base {
    virtual void some_func(float) override;
};

我认为 override 不是C ++关键字,那么它真的意味着什么?

I thought override was not a C++ keyword, so what does it really mean? We can achieve the same thing without that keyword so why would anyone need it?

还有一个关键字 final 它在VS2010上还不工作:

There is also the keyword final which does not yet work on VS2010 :

struct Base1 final { };

struct Derived1 : Base1 { }; // ill-formed because the class Base1 
                             // has been marked final


推荐答案

在C ++ 11中, override final

In C++11, override and final are "identifiers with special meaning". They are not keywords and only acquire special meaning if used in a specific context (when declaring virtual functions).

这个想法是允许编译器捕获某些类型的错误,它们不是关键字,只有在特定上下文中使用通过允许程序员显式地声明它们的意图(例如,重写一个现有的虚函数而不是创建一个新的)。

The idea is to enable to compiler to catch certain types of errors by allowing the programmer to explicitly state their intent (e.g. to override an existing virtual function rather than create a new one).

这是标准的相关报价,示例:

Here is the relevant quote from the standard, with examples:


C ++ 11 10.3 4如果某个类B中的虚函数f
virt-specifier final ,在D类派生自B的函数D :: f
覆盖B :: f,形成。 [示例:

C++11 10.3 4 If a virtual function f in some class B is marked with the virt-specifier final and in a class D derived from B a function D::f overrides B::f, the program is ill-formed. [ Example:

struct B {
virtual void f() const final;
};
struct D : B {
void f() const; // error: D::f attempts to override final B::f
};

-end示例]

虚函数用virt-specifier override
标记,并且不覆盖基类的成员函数,程序
未生成。 [示例:

5 If a virtual function is marked with the virt-specifier override and does not override a member function of a base class, the program is ill-formed. [ Example:

struct B {
virtual void f(int);
};
struct D : B {
void f(long) override; // error: wrong signature overriding B::f
void f(int) override; // OK
};

-end example]

—end example ]

这篇关于显式覆盖和最终c ++ 0x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆