C++ 标头中的哪些关键字进入 cpp 文件?

问题描述 投票:0回答:1

如果我将代码拆分为 .h 和 .cpp 文件,则标头中使用的以下关键字中哪些也必须在 .cpp 文件中使用,并且不得进入 .cpp 文件中:

const, virtual, override, noexcept, constexpression

以及必须按什么顺序使用它们,即以下顺序是否正确:

virtual constexpression int foo() const override noexcept;

如果存在,请随意给出规则。

c++ header keyword
1个回答
0
投票

“虚拟”说明符是类定义的一部分,仅属于类成员规范,在本例中是非静态类成员函数的声明(带或不带定义)。

“限定符”(const、volatile、

&
&&
)是函数的一部分,因此必须出现在(成员)函数的每个声明中(包括定义函数,无论是内联函数还是外联函数)线):

// Class definition of X; specifies the members of X.
struct X : Base {
  virtual void f() const;  // virtual and override
  void g() && override;    // are part of "being a member"
};

// Function declarations and definitions:
// qualifiers are part of the function.
void X::f() const { /* ... */ }
void X::g() &&    { /* ... */ }

这与 .h 和 .cpp 文件本身无关,尽管人们通常会将外联定义放入 .cpp 文件中。 (如果将其保留在标头中,则会导致重复定义,因为标头包含在不同的翻译单元中,除非其中一个声明也显式指定为

inline
。相比之下,类成员函数的内联定义是隐式的
inline
。)

© www.soinside.com 2019 - 2024. All rights reserved.