基类私有虚函数可被派生类重写

基类私有虚函数可被派生类重写。

基类的私有成员不可以被派生类访问,没想到可以重写基类的虚函数,而且动态绑定。看来对虚函数还有待理解。

#include <iostream>
using namespace std;
class Base
{
    public:
        ~Base(){}
        int fun(){
            prFun();
        }
    private:
        virtual void prFun(){
            cout << "I am base's private function\n";
        }
};

class Derived: public Base
{
    public:
        void prFun(){
            cout << "I am derived function\n";
        }
};


int main()
{
    Base b;
    Derived d;
    Base *p = &d;
    b.fun();  //Base's prFun
    d.fun();  // Derived's prFun
    p->fun(); // Derived's prFun
    return 0;
}

你可能感兴趣的:(基类私有虚函数可被派生类重写)