C++將struct/class的成員保護(hù)粒度劃分為:public、protected、private,這在語(yǔ)言入門(mén)時(shí)就應(yīng)知曉的。然而前幾天遇到的一段代碼,卻讓我琢磨了許久:
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可以直接通過(guò)成員訪(fǎng)問(wèn)運(yùn)算符訪(fǎng)問(wèn)?
我開(kāi)始意識(shí)到自己對(duì)成員保護(hù)機(jī)制的認(rèn)識(shí)有誤,不知從什么時(shí)候起"對(duì)象.私有成員"的模式在大腦中就被一票否定了,這意味著默認(rèn)了成員保護(hù)機(jī)制是針對(duì)對(duì)象的。然而,"The Annotated C++ Reference Manual"對(duì)保護(hù)機(jī)制的精辟總結(jié):
(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
明確指出成員保護(hù)機(jī)制是針對(duì)類(lèi)的,且為編譯時(shí)機(jī)制。仔細(xì)一想,C++從來(lái)就未有在運(yùn)行時(shí)檢查成員訪(fǎng)問(wèn)合法性的機(jī)制,所有的檢查都在編譯期完成,此時(shí)根本不會(huì)產(chǎn)生對(duì)象,因而之前對(duì)該機(jī)制的認(rèn)知是有問(wèn)題的。BTW,第一點(diǎn)總結(jié)得甚好,運(yùn)行時(shí)可通過(guò)私有成員指針在外部訪(fǎng)問(wèn)的原因應(yīng)該很清楚了吧(這被認(rèn)為是fraud,:P)。
生活、工作中會(huì)有各種各樣認(rèn)知誤區(qū),與自己認(rèn)知相悖的,不一定是錯(cuò)誤的,要搜尋客觀(guān)證據(jù),理性思考。