重写不受限制

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class A
{
    public:
        virtual int getMile()
        {
            return getPerGallon() * getGallon();
        }
        virtual void setGallon(int gallon)
        {
            mGallon = gallon;
        }
        
        virtual int getGallon()
        {
            return mGallon;
        }
    private:
        int mGallon;
        virtual int getPerGallon()
        {
            return 20;
        }
};

class B : public A
{        
    public:
        virtual int getPerGallon()
        {
            return 35;
        }    
};

int main(int argc, char** argv) 
{
    B b;
    A a;
    b.setGallon(2);
    a.setGallon(2);
    std::cout << "B have ride " << b.getMile() << std::endl;
     std::cout << "A have ride " << a.getMile() << std::endl;
     /*
    B have ride 70
    A have ride 40    
     */
    return 0;
}

虚函数不仅可以定义在public,而且可以声明在protected和private里边

而在派生类里边可以定义在任何限定里边,不一定和父类的限制符相同,比如:父类的在private里,但是子类可以定义在public里

猜你喜欢

转载自www.cnblogs.com/boost/p/10346293.html