這篇文章主要介紹“C++怎么實現最小限度暴露成員”,在日常操作中,相信很多人在C++怎么實現最小限度暴露成員問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C++怎么實現最小限度暴露成員”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
C.9:最小限度暴露成員
Reason(原因)
Encapsulation. Information hiding. Minimize the chance of unintended access. This simplifies maintenance.
封裝性。信息隱藏。將非故意訪問的可能性降至最低。簡化維護。
譯者注:這是封裝最直接的好處。
Example(示例)
template<typename T, typename U>struct pair { T a; U b; // ...};
無論我們在注釋的位置做什么,pair的任何用戶都可以隨意、獨立的修改數據成員a和b。在大規模代碼中,我們無法簡單地發現是哪段代碼對pair的成員做了什么。如果這就是我們想要的當然沒問題,但是如果我們想要加強成員間聯系,就需要將它們變更為私有成員并通過構造函數和成員函數強化這種聯系(不變式)。例如:
class Distance {public: // ... double meters() const { return magnitude*unit; } void set_unit(double u) { // ... check that u is a factor of 10 ... // ... change magnitude appropriately ... unit = u; } // ...private: double magnitude; double unit; // 1 is meters, 1000 is kilometers, 0.001 is millimeters, etc.};If the set of direct users of a set of variables cannot be easily determined, the type or usage of that set cannot be (easily) changed/improved. For public and protected data, that's usually the case.
如果無法簡單地決定一組變量的直接用戶,這組變量的類型和用法就無法(簡單地)變更和改善。公有或保護成員,基本上屬于這種情況。
Example(示例)
A class can provide two interfaces to its users. One for derived classes (protected) and one for general users (public). For example, a derived class might be allowed to skip a run-time check because it has already guaranteed correctness:
一個類可以向用戶提供兩類接口。一類面向派生類(保護成員),一個面向普通用戶(公有成員)。例如,由于已經保證了正確性,某個派生類可能會允許省略某項運行時檢查。
class Foo {public:int bar(int x) { check(x); return do_bar(x); }// ...protected:int do_bar(int x); // do some operation on the data// ...private:// ... data ...};class Dir : public Foo {//...int mem(int x, int y){/* ... do something ... */return do_bar(x + y); // OK: derived class can bypass check}};void user(Foo& x){int r1 = x.bar(1); // OK, will checkint r2 = x.do_bar(2); // error: would bypass check// ...}
protected data is a bad idea.
保護型數據是個壞主意。
Note(注意)
Prefer the order public members before protected members before private members see.
較好的順序是公有成員在保護成員之前,保護成員又在私有成員之前。
譯者注:還有一個類似的規則是:如果成員之間有調用關系,那么調用者在前,被調用者在后。
Enforcement(實施建議)
Flag protected data.
在發現保護型數據時進行提示。
Flag mixtures of public and private data
在發現公有和私有數據混雜在一起時進行提示。
到此,關于“C++怎么實現最小限度暴露成員”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。