如何组织类的成员函数?

How to organize a class's member functions?

本文关键字:函数 成员 何组织      更新时间:2023-10-16

我将"sets"放在构造函数之后,因为它与对象设置有关。我拆分了get(放入查询(和集合,但不确定这是否好。组织成员功能的最佳实践是什么?

怎么样?

class Foo
{
// Friends go here if it has
friend ...;
friend ...;
// First public, then protected and private
public:
    // enums
    enum {...}
    // type defines.
    typedef ...;
    ...
    // Destructor and constructors
    ~Foo();
    Foo(...);
    Foo(...);
    ...
    // Sets.
    void setA(...);
    void setB(...);
    void setC(...);
    ...
    // Inquiries (including gets).
    A a() const;
    B b() const;
    ...
    // Operators.
    void operator()(...);
    ...
    // Operations.
    void doSomething();
    ...
protected:
private:
};

很难判断,这取决于您的个人喜好或公司编码标准。通过查看您的代码,我可能不同意以下几点:

  • 您的声明不是从pubilc订购的,"受保护"然后是私人的
  • 当您在私人区域声明它们时,friend声明也有相同的努力。 所以我通常将它们放在私人部分,因此它在public section中产生的噪音较小。

以下是我通常使用的申报顺序

在类中使用指定的声明顺序:public:在private之前:,在数据成员(变量(之前的方法等。

类定义应该从它的public:部分开始,然后是它的protected:部分,然后是它的private:部分。如果这些部分中的任何一个为空,请省略它们。

在每个部分中,声明通常应按以下顺序排列:

Typedefs and Enums
Constants (static const data members)
Constructors
Destructor
Methods, including static methods
Data Members (except static const data members)

好友声明应始终位于私有部分,禁用copy constructor和其他操作员应位于私有:部分的末尾。这应该是课堂上的最后一件事。