c++ - 带有尾随返回类型的 final、override、const 的语法

标签 c++ c++11 syntax

我正在尝试覆盖虚拟,但也使用关键字 overridefinalconst,以及尾随返回类型。问题似乎出在派生类中,编译器错误(说我没有指定尾随返回类型)并没有太大帮助。代码在这里:https://wandbox.org/permlink/zh3hD4Ukgrg6txyE

也贴在下面。我玩过不同的顺序,但似乎仍然无法正确处理。任何帮助将不胜感激,谢谢。

#include<iostream>
using std::cout; using std::endl; using std::ostream;
//////////////////////////////////////////////
//Base stuff
class Base
{
public:
  Base(int i=2):bval(i){}
  virtual ~Base()=default;
  virtual auto debug(ostream& os=cout)const->ostream&;

private:
  int bval=0;
};

auto Base::debug(ostream& os) const->ostream&
{
  os << "bval: " << bval << endl;
  return os;
}

///////////////////////////////////////////////
//Derived stuff
class Derived : public Base
{
public:
  Derived(int i=2,int j=3):Base(i), dval(j){}
  ~Derived()=default;

  auto debug(ostream& os=cout) const override final->ostream&; // error here

private:
  int dval=0;
};

auto Derived::debug(ostream& os) const override final->ostream&
{
  os << "dval: " << dval << endl;
  return os;
}

///////////////////////////////////////////////
//Testing!
int main()
{
  Base b(42);
  b.debug()<<endl;
  return 0;
}

最佳答案

正确的语法应该是:

  1. overridefinal应该出现在成员函数声明之后,其中包括尾随返回类型规范,即

    auto debug(ostream& os=cout) const ->ostream& override final;
    
  2. overridefinal 不应与类定义之外的成员函数定义一起使用,因此只需删除它们:

    auto Derived::debug(ostream& os) const ->ostream&
    {
      os << "dval: " << dval << endl;
      return os;
    }
    

关于c++ - 带有尾随返回类型的 final、override、const 的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43560697/

相关文章:

c++ - 在 visual studio 2012 中管理 c++11 线程

java - 为什么 MongoDB Java 驱动程序/Morphia 两次预先设置一个属性?

arrays - 如何让 VBA 子程序调用一个函数,该函数将数组传递给子程序中的另一个函数

c++ - 多个子进程的 PID 从同一个父进程中 fork 出来

c++ - 原子引用计数

c++ - Poco HTTPClientSession 将 header 添加到 HTTPRequest

c++ - 默认的默认构造函数?在 n3290 草案中

c++ - 构建同一 C/C++ 应用程序的变体的最佳方法是什么

c++ - 错误读取变量 : Could not find the frame base

go - 申报后无法进口