本文介绍了脱机定义成员函数时,哪些限定符必须出现在声明/定义/两者中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎可以肯定这已经被问过了.不幸的是,我的C ++变得如此生锈,以至于我什至都不知道要搜索什么.

I am almost sure this has been asked before. Unfortunately, my C++ has become so rusty that I don't even know what to search for.

是否有容易记住的经验法则,告诉我哪些限定词(inlinevirtualoverrideconstmutable等)必须出现(a)在声明中,(b)仅在定义中,(c)当我离线定义成员函数时,在声明和定义中都如此?

Is there an easy-to-remember rule of thumb that would tell me which qualifiers (inline, virtual, override, const, mutable, etc.) must appear (a) only in the declaration, (b) only in the definition, (c) both in the declaration and definition when I define a member function out-of-line?

struct Geometry {
    …
    virtual Geometry* clone() const = 0;
};

struct Point2 : public Geometry {
    …
    virtual Point2* clone() const override { … }
};

如果我要脱机定义Point2::clone,则反复试验会使我相信这将是正确的代码:

If I wanted to define Point2::clone out-of-line, trial and error leads me to believe that this would be the correct code:

struct Point2 : public Geometry {
    …
    virtual Point2* clone() const override;
};

Point2* Point2::clone() const { … }

  • virtualoverride限定词可能在声明中仅出现 .
  • const必须同时出现在 声明和定义中.
    • The virtual and override qualifiers may appear only in the declaration.
    • const must appear in both the declaration and definition.
    • 我不想永远依靠反复试验.但是我想明确说明限定词(即,即使例如基类隐含了限定词,也要重复它们.)是否存在一个通用规则,即限定词必须精确地定位在哪里,或者每个规则是否不同?

      I would not want to rely on trial and error forever. But I want to be explicit about qualifiers (i.e. repeat them even if e.g. they are implied by a base class.) Is there a general rule which qualifier has to go exactly where, or are the rules different for each of them?

      推荐答案

      一般规则是,删除限定符会产生不同的函数重载,该限定符必须出现在两个位置.所有其他限定词都保留在声明中.

      General rule is that when removing a qualifier produces a different function overload, that qualifier must appear in both places. All other qualifiers stay in the declaration.

      在两个地方都必须出现的三个限定词是const和在C ++ 11标准中出现的两种参考限定词:

      The three qualifiers that must appear in both places are const and the two kinds of reference qualifiers, which appear in the C++11 standard:

      void foo() const;
      void foo() &;
      void foo() &&;
      

      所有其他限定词都保留在声明中.

      All other qualifiers stay in the declaration.

      这篇关于脱机定义成员函数时,哪些限定符必须出现在声明/定义/两者中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 22:52