zoukankan      html  css  js  c++  java
  • 多态性与虚函数之重载和重新定义

    重新定义一个基类中的重载函数将会隐藏所有该函数的其他基类版本。而当对虚函数进行这些操作时,情况会有所不同。我们先来看下面例子:

    class Base {
    public:
        virtual int f() const {
            cout<<"Base::f()\n";
            return 1;
        }
    
        virtual void f(string) const { }
    
        virtual void g() const { }
    };
    
    class Derived1: public Base {
    public:
        void g() const { }
    };
    
    class Derived2: public Base {
    public:
        //overriding a virtual function:
        int f() const {
            cout<<"Derived2::f()\n";
            return 2;
        }
    };
    
    class Derived3: public Base {
    public:
        //cannot change return type:
         //!void f() const { cout<<"Derived3::f()\n"; }
    };
    
    class Derived4: public Base {
    public:
        //change argument list:
        int f(int) const {
            cout<<"Derived4::f()\n";
            return 4;
        }
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        string s("hello");
        Derived1 d1;
        int x = d1.f();
        d1.f(s);
    
        Derived2 d2;
        x = d2.f();
        //d2.f(s);//string version hidden
    
        Derived4 d4;
        x = d4.f(1);//int version only
        //x = d4.f(); // f() version hidden
    
        Base& br = d4;//Upcast
        br.f();
        br.f(s);
        //br.f(1); //Derived version unavailable
        system("pause");
    
        return 0;
    }
  • 相关阅读:
    2019年CSP-J初赛试题(普及组)试题详解
    开放课件
    猴子选大王 (约瑟夫问题)
    后缀表达式转中缀表达式
    JDBC的使用
    JDBC
    MySQL第五天
    MySQL第四天
    MySQL第三天
    MySQL第二天
  • 原文地址:https://www.cnblogs.com/wiessharling/p/3090380.html
Copyright © 2011-2022 走看看