简体   繁体   中英

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

Ie. When I have a class say

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

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

And I wanted to call it in another class like main to assign to the variable colors.

#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;
 }

When is the correct time to use either?

The answer is: it depends.

On you, your preferences, the coding guidelines of your team, how OO your code is, even the syntactic sugar your language offers, etc. Also this quickly becomes a question of usable/readable code.

My (arguably general) advice is: whenever you are writing simple code and your class resembles data more than objects, it is totally OK to give public access to your members (you might want to use structs in C++ though instead of a class, just to make your decision more obvious). Not only is this easier to write in the first place, it is easier to use an read than endless get-set combinations.

On the other end of the spectrum getters and setters allow you to control access to your internal members, eg for validation, or to update the internal state accordingly. AFAIK this is encapsulation and keeps more complicated OO-code sane.

Just avoid having both methods for the same members, this quickly becomes confusing and irritating.

除静态变量外,最好始终使用getter和setter方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM