带尾返回类型的 final、override 和 const 的语法

8
我想重写一个虚函数,并使用关键词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;
}

小细节,你不需要 ~Derived()=default; 对吧? - Sheen
1个回答

9
正确的语法应该是:

正确的语法应该是:

  1. override and final should appear after the member function declaration, which including the trailing return type specification, i.e.

    auto debug(ostream& os=cout) const ->ostream& override final;
    
  2. override and final should not be used with the member function definition outside the class definition, so just remove them:

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

哦,当然,忘记返回os了,谢谢!问题:你是如何记住这些规范的语法的?还是说只是随着时间的推移自然而然地掌握的?或者有什么规则我应该知道吗?我总是很难记住应该只在类成员声明中出现的内容以及可以在声明和定义中同时出现的内容,并且不知道应该把什么放在哪里(例如,尾随返回应该在overrideconst之前)。 - pss
2
@pss 声明和定义中都可以包含什么内容 -- 我的经验法则是:如果你可以对某些东西进行重载,那么它必须在声明和定义中都存在。 - zett42
3
@pss 尾置返回类型规范是函数声明的一部分(即函数签名的一部分),但 finaloverride 不是。因此,您不应将它们放在函数声明的中间。作为函数签名的一部分,尾置返回类型规范可以(而且应该)被指定为声明和定义的一部分,但 finaloverride 只能在类定义内部指定;它们用于与类和继承相关的某些特性,但不涉及实现。 - songyuanyao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接