C++ 何时是使用无默认构造函数与 getter 和 setter 与仅直接调用 class 中的变量的正确时间

C++ when is the right time to use a no default constructor vs. getters and setters vs just invoking the variables in the class directly

即。当我有 class 说

class color()
{
     Private:
     std:: string _colors

  Public:
   color();
   color(std::string colors);
   std::string setColors(std::string colors);
  std::string colors;
  ~color();
}

我想在另一个 class 中像 main 一样调用它来分配给变量颜色。

#include "color.h"

using namespace std;
int main()
{
  color C;
  C.colors = "Blue"; //is this correct
  color("Blue"); //is this correct
 C.setColors("Blue");//or is this correct.
 return 0;
 }

什么时候使用两者的正确时间?

除了静态变量外,使用 getter 和 setter 始终是一个好习惯。

答案是:视情况而定。

关于你,你的喜好,你的团队的编码指南,你的代码是如何面向对象的,甚至你的语言提供的语法糖等等。这很快就变成了 usable/readable 代码的问题。

我的(可以说是一般性的)建议是:每当您编写简单的代码并且您的 class 更像数据而不是对象时,完全可以为您的成员提供 public 访问权限(您可能想在 C++ 中使用结构而不是 class,只是为了让你的决定更明显)。这不仅首先更容易编写,而且使用读取比无休止的 get-set 组合更容易。

另一方面,getter 和 setter 允许您控制对内部成员的访问,例如用于验证,或相应地更新内部状态。 AFAIK 这是封装并使更复杂的 OO 代码保持正常。

只要避免对同一成员使用这两种方法,这很快就会变得令人困惑和恼火。