zoukankan      html  css  js  c++  java
  • 重写不受限制

    #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里

  • 相关阅读:
    Java 集合框架
    Java 网络编程
    Java序列化
    Java 发送邮件
    Java 多线程编程
    Java 文档注释
    Java Applet基础
    Python 基础教程
    Python 简介
    一步步学习SPD2010--第三章节--处理列表和库(19)----关键点
  • 原文地址:https://www.cnblogs.com/boost/p/10346293.html
Copyright © 2011-2022 走看看