为什么头文件中有多个“公共”关键字?

abi*_*901 3 c++ access-modifiers header-files

我是一名新编码员,因此请原谅我提出一个非常简单的问题。我正在查看要实现的方法的一些示例代码,并且看到下面显示的标头(第一段代码)。

class CIndividual  
{

public:
    CIndividual();
    virtual ~CIndividual();

public:
         vector<int> profit;
       vector<int> weight;    

public:
    CRandomNumber Rnd;
    bool dominated;
};
Run Code Online (Sandbox Code Playgroud)

为什么公众多次使用?我对这种编码结构感到非常困惑,希望这个问题不太基本。

Wag*_*ota 5

在上述情况下,第一个只有一个就足够了。所有其他都是多余的。有些人喜欢重写这些关键字,以显式地“分隔”方法和成员变量的块,但在这种情况下并没有真正的需要。只是喜好问题。

class MyClass
{
public:
  void myPublicMethod1();
  void myPublicMethod2();

private:
  myPrivateMethod();

private:                         // redundant, just group variables
  int somePrivateVariable;       // the first "private" should be enough as well
  string anotherPrivateVariable;

public:                          // not redundant here, but the variables
  int publicMember1;             // could be moved to the first group, if desired.
  bool publicMember2;
};
Run Code Online (Sandbox Code Playgroud)