本篇內容主要講解“C++為什么只有直接訪問表達的函數才成為成員”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“C++為什么只有直接訪問表達的函數才成為成員”吧!
C.4:只有直接訪問表達的函數,才應該成為成員。
Reason(原因)
和使用成員函數相比普通函數耦合性略低,一方面可以通過修改對象狀態帶來麻煩的函數會變少,另一方面可以減少改變類表達時需要修改的函數的數量。
Example(示例)
class Date {
// ... relatively small interface ...
};
// helper functions:
Date next_weekday(Date);
bool operator==(Date, Date);
The "helper functions" have no need for direct access to the representation of a Date
.
“幫助函數”沒有需求要直接訪問Data的表達。
Note(注意)
This rule becomes even better if C++ gets "uniform function call".
如果C++可以導入“統一函數調用”這條準則甚至會變得更完美。
譯者注:“uniform funcation call”是C++之父本人提出的C++語法建議。核心是對于一個形如f(x,y)的函數調用,如果不存在函數f(x,y),可以轉而調用x.f(y)。有了這個語法,編寫非成員幫助函數的靈活性將會進一步加大。
Exception(例外)
(C++)語言要求虛函數必須是成員,而且不是所有的虛函數都會直接訪問數據。通常抽象類的成員很少直接訪問數據。
Note multi-methods.
Exception(類外)
The language requires operators =
, ()
, []
, and ->
to be members.
語言要求=,(),[]和->運算符作為成員存在。
Exception(列外)
An overload set may have some members that do not directly access private
data:
一組重載函數中也許會有某個成員不會直接訪問私有數據。
class Foobar {public: void foo(long x) { /* manipulate private data */ } void foo(double x) { foo(std::lround(x)); } // ...private: // ...};
Exception(例外)
Similarly, a set of functions may be designed to be used in a chain:
類似地,一組函數可能被設計用來串聯使用。
x.scale(0.5).rotate(45).set_color(Color::red);
Typically, some but not all of such functions directly access private
data.
通常,有些但不是所有這樣的函數都會直接訪問私有數據
Enforcement(實施建議)
Look for non-virtual
member functions that do not touch data members directly. The snag is that many member functions that do not need to touch data members directly do.
尋找沒有直接接觸數據成員的非虛成員函數。諷刺的是存在許多不需要直 接訪問數據成員的成員函數。
Ignore virtual
functions.
忽略虛函數。
Ignore functions that are part of an overload set out of which at least one function accesses private
members.
如果一組重載函數中至少有一個函數訪問了私有成員,那么忽略其他函數。
Ignore functions returning this
.
忽略返回this指針的函數。
到此,相信大家對“C++為什么只有直接訪問表達的函數才成為成員”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。