C++將struct/class的成員保護粒度劃分為:public、protected、private,這在語言入門時就應知曉的。然而前幾天遇到的一段代碼,卻讓我琢磨了許久:
class Record
{
public:
Record& operator= (const Record& r)
{
file = r.file;
offset = r.offset;
return *this;
}
...
private:
unsigned char *offset;
NBFile &file;
...
};
為什么作為private成員的offset和file可以直接通過成員訪問運算符訪問?
我開始意識到自己對成員保護機制的認識有誤,不知從什么時候起"對象.私有成員"的模式在大腦中就被一票否定了,這意味著默認了成員保護機制是針對對象的。然而,"The Annotated C++ Reference Manual"對保護機制的精辟總結:
(1) Protection is provided by compile-time mechanisms against accident, not against fraud or explicit violation.
(2) Access is granted by a class, not unilaterally taken.
(3) Access control is done for names and does not depend on the type of what is named.
(4) The unit of protection is the class, not the individual object.
(5) Access is controlled, not visibility
明確指出成員保護機制是針對類的,且為編譯時機制。仔細一想,C++從來就未有在運行時檢查成員訪問合法性的機制,所有的檢查都在編譯期完成,此時根本不會產生對象,因而之前對該機制的認知是有問題的。BTW,第一點總結得甚好,運行時可通過私有成員指針在外部訪問的原因應該很清楚了吧(這被認為是fraud,:P)。
生活、工作中會有各種各樣認知誤區,與自己認知相悖的,不一定是錯誤的,要搜尋客觀證據,理性思考。