今天寫代碼竟然發現,成員函數竟然可以在類的外部調用,開始以為是C++
#include <iostream>using namespace std; class Base{public:virtual void Func(){cout<<"base"<<endl;}};class Derived : public Base{private:void Func(){cout<<"derived"<< endl;}};int main(){Base *d = new Derived;d->Func( );delete d;return 0;}
查看了一下資料,發下了下面的內容,這下一下子就明了了。
/*參考C++ Standard ISO/IEC 14882:2003(E) 第11.6節:11.6 Access to virtual functions [class.access.virt]The access rules (clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it. [Example:*/class B {public:virtual int f();};class D : public B {private:int f();};void f(){D d;B* pb = &d;D* pd = &d;pb->f(); //OK: B::f() is public,// D::f() is invokedpd->f(); //error: D::f() is private}/*—end example]Access is checked at the call point using the type of the expression used to denote the object for which the member function is called (B* in the example above). The access of the member function in the class in which it was defined (D in the example above) is in general not known.*/
我們知道
我們可以想像:當一個子類的虛成員函數通過基類的指標調用時,存取權限取決於基類對該函數的聲明,而C++private僅僅是一個訪問限定符,它只限定函數和資料不能被“直接”訪問,而不擔保這些函數和資料會被通過其他方法間接地訪問到,在成員函數中返回一個類私人資料成員的引用,在外部就可以對這個私人屬性進行修改(這個請參照博主的,對這個現象有說明)也是這個道理。