private成員函數竟然可以在類的外部調用

來源:互聯網
上載者:User

今天寫代碼竟然發現,成員函數竟然可以在類的外部調用,開始以為是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僅僅是一個訪問限定符,它只限定函數和資料不能被“直接”訪問,而不擔保這些函數和資料會被通過其他方法間接地訪問到,在成員函數中返回一個類私人資料成員的引用,在外部就可以對這個私人屬性進行修改(這個請參照博主的,對這個現象有說明)也是這個道理。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.