NL.16: Use a conventional class member declaration order
NL.16:使用常规的类成员声明顺序
Reason(原因)
A conventional order of members improves readability.
常规的成员顺序可以提高可读性。
When declaring a class use the following order
当声明一个类时,使用以下顺序
- types: classes, enums, and aliases (using) 类型:类,枚举和别名(using)
- constructors, assignments, destructor 构造函数,赋值,析构函数
- functions 成员函数
- data 数据成员
Use the public before protected before private order.
使用公有成员处于保护成员之前,保护成员处于私有成员之前的顺序。
This is a recommendation for when you have no constraints or better ideas. This rule was added after many requests for guidance.
当您没有其他约束或更好的主意时,考虑这个建议。此规则可以作为许多准则之外的要求。
Example(示例)
代码语言:javascript复制class X {
public:
// interface
protected:
// unchecked function for use by derived class implementations
private:
// implementation details
};
Example(示例)
Sometimes, the default order of members conflicts with a desire to separate the public interface from implementation details. In such cases, private types and functions can be placed with private data.
有时,成员的默认顺序与将公共接口与实现细节分开的期望相冲突。在这种情况下,可以将私有类型和函数与私有数据一起放置。
代码语言:javascript复制class X {
public:
// interface
protected:
// unchecked function for use by derived class implementations
private:
// implementation details (types, functions, and data)
};
Example, bad(反面示例)
Avoid multiple blocks of declarations of one access (e.g., public) dispersed among blocks of declarations with different access (e.g. private).
避免将一个访问权限(例如公共)的多个声明块分散在具有不同访问权限(例如私有)的声明块之间。
代码语言:javascript复制class X { // bad
public:
void f();
public:
int g();
// ...
};
The use of macros to declare groups of members often leads to violation of any ordering rules. However, macros obscures what is being expressed anyway.
使用宏声明成员组通常会导致违反所有排序规则。但是,宏仍然掩盖了正在表达的内容。
Enforcement(实施建议)
Flag departures from the suggested order. There will be a lot of old code that doesn't follow this rule.
标记偏离建议的顺序。会有很多旧代码没有遵循此规则。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nl16-use-a-conventional-class-member-declaration-order