constexpr虚方法编译报错:返回类型冲突?关键字顺序疑问
编译错误分析:虚函数override与尾置返回类型的顺序问题
以下代码编译失败,编译器提示返回类型冲突,但移除override关键字后可正常编译:
#include <string_view> #include <cstdio> struct base { virtual constexpr auto delimiter() const noexcept -> std::string_view = 0; }; struct derived : public base { constexpr auto delimiter() const noexcept override -> std::string_view { return "/"; } }; int main() { }
编译错误信息
<source>:11:47: error: expected ';' at end of member declaration 11 | constexpr auto delimiter() const noexcept override -> std::string_view { return "/"; } | ^~~~~~~~ | ; <source>:11:56: error: expected unqualified-id before '->' token 11 | constexpr auto delimiter() const noexcept override -> std::string_view { return "/"; } | ^~ <source>:11:20: error: conflicting return type specified for 'virtual constexpr auto derived::delimiter() const' 11 | constexpr auto delimiter() const noexcept override -> std::string_view { return "/"; } | ^~~~~~~~~ <source>:6:28: note: overridden function is 'virtual constexpr std::string_view base::delimiter() const' 6 | virtual constexpr auto delimiter() const noexcept -> std::string_view = 0; |
错误原因
核心问题是**override关键字的位置不符合C++语法规则**:
当使用尾置返回类型(-> 返回类型)时,override作为函数说明符,必须放在尾置返回类型的后面,而非前面。代码中将override放在了noexcept与尾置返回类型之间,导致编译器误解析:它会认为函数声明在override处结束,要求添加分号,后续的-> std::string_view被视为无效语法,最终引发返回类型冲突的错误。
解决方法
将override移动到尾置返回类型的后方,修正后的代码如下:
#include <string_view> #include <cstdio> struct base { virtual constexpr auto delimiter() const noexcept -> std::string_view = 0; }; struct derived : public base { constexpr auto delimiter() const noexcept -> std::string_view override { return "/"; } }; int main() { }
或者,也可以改用前置返回类型的写法,此时override放在函数声明末尾即可:
struct derived : public base { constexpr std::string_view delimiter() const noexcept override { return "/"; } };
内容的提问来源于stack exchange,提问作者glades
相关产品推荐
相关产品推荐

