[英]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瀏覽器。 當我上課時說
class color()
{
Private:
std:: string _colors
Public:
color();
color(std::string colors);
std::string setColors(std::string colors);
std::string colors;
~color();
}
我想在另一個類(例如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;
}
什么時候才是正確的時間?
答案是:這取決於。
在您身上,您的喜好,團隊的編碼准則,代碼的面向對象,甚至您的語言提供的語法糖等等。這也很快成為可用/可讀代碼的問題。
我的(可以說是一般性的)建議是:每當您編寫簡單的代碼並且類比對象更像數據時,向成員提供公共訪問是完全可以的(您可能想在C ++中使用結構而不是類,只是使您的決定更加明顯)。 首先,這不僅容易編寫,而且比無限的獲取集組合更易於使用讀取。
在頻譜的另一端,getter和setter允許您控制對內部成員的訪問,例如進行驗證或相應地更新內部狀態。 AFAIK這是封裝,並保持更復雜的OO代碼合理。
只是避免對相同的成員使用兩種方法,這很快就會造成混亂和煩人。
除靜態變量外,最好始終使用getter和setter方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.