C++11 具有新的 override
限定符,可应用于成员函数以断言它们覆盖基类中的虚函数。 C++11 还允许尾随返回类型,因此函数可以声明为 auto f() -> return_type
。当我结合这两个功能时,我不知道 override
是在 ->
之前还是之后。
例如,假设我们有以下基类:
struct Base {
virtual auto f () const -> int = 0;
};
派生类的两种可能性是:
struct Derived : public Base {
virtual auto f () const override -> int { return 0; } // Compiles on g++ 4.7.1
};
或
struct Derived : public Base {
virtual auto f () const -> int override { return 0; } // Compiles on clang++ 4.0
};
g++ 4.7.1 编译了第一个版本,但在第二个版本中失败了
test.cpp:6:30: error: expected ';' at end of member declaration
test.cpp:6:34: error: 'override' does not name a type
而 clang++ 4.0 编译第二个,但在第一个失败
test.cpp:6:11: error: 'auto' return without trailing return type
virtual auto f () const override -> int { return 0; }
^
test.cpp:6:3: error: only virtual member functions can be marked 'override'
virtual auto f () const override -> int { return 0; }
^ ~~~~~~~~
test.cpp:6:35: error: expected ';' at end of declaration list
virtual auto f () const override -> int { return 0; }
这些编译器中的哪一个实际上根据标准在做正确的事情?
编辑: 正如 Kerrek SB 所说,这是 a bug in gcc (Bugzilla link) .
最佳答案
根据标准,8.4.1,一个函数的declarator包含trailing-return-type,一个类函数定义包含“declarator virt-specifier-seqopt"。第二个,virt-specifier-seq,是 final
或 override
之一,所以它们在 之后尾随返回类型。 (即 Clang 做对了。)
关于c++ - 'override' 限定符与尾随返回类型一起去哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771005/