• 关于virtual、非virtual继承函数的调用


    内容声明:转自http://www.cppblog.com/liyuxia713/archive/2010/01/08/105170.html

    由于登录问题,没能直接转载,所以直接贴别人的博客。侵权请直接联系本人博客。

    类成员函数继承(virtual、非virtual)
    类继承
    ★ 对于父类函数(virtual、非virtual),如果子类没有同名函数,则正常继承
    ★ 对于父类函数(virtual、非virtual),如果子类有同名函数,无同型函数,则不能调用父类函数
    ★ 对于父类函数(virtual、非virtual),如果有同型函数:
    ----非virtual函数由指针类型决定调用哪个
    ----virtual函数由指针指向的对象决定调用哪个(运行时决定)

    //如果对于父类函数(virtual/非virtual),如果子类没有同名函数,则正常继承
    
    class Base{
    public:  
        void func(int i){ cout <<"Base::func(int)"<< endl; }    
    }; 
    
    class Derived : public Base
    { }; 
    
    int main()
    {
        Base *pb = new Derived();
        pb->func(1); //Base::func(int)
        delete pb; 
     
        Derived *pd = new Derived();
        pd->func(1); //Base::func(int)
        delete pd;
    }
    View Code
    //对于父类函数(virtual、非virutal),子类有同名函数,无同型函数,则不能调用父类函数
    class Base
    {
    public:
         void func(int i){ cout <<"Base::func(int i)"<< endl; } 
         virtual void func2(int i) { cout << "Base::func2(int i)" << endl;}
    }; 
    
    class Derived : public Base{
    public:      
          void func(){ cout <<"Derived::func()"<< endl; } 
          void func2(){ cout <<"Derived::func2()"<< endl; } 
    }; 
    
    int main()
    {
        Base *pb = new Derived();
        pb->func(1); //Base::func(int)
        pb->func2(1); //Base::func2(int i)
        delete pb;
    
        Derived *pd = new Derived();
        pd->func(); //Derived::func()
        pd->func2(); //Derived::func2()
        // pd->func2(1); //不能调用 
        delete pd;       
    
    }
    View Code
    //对于父类函数(virtual、非virtual),如果有同型函数:
    //----非virtual函数由指针类型决定调用哪个
    //----virtual函数由指针指向的对象决定调用哪个(运行时决定)
    class Base
    {
    public:
        void func(int i){ cout <<"Base::func(int i)"<< endl; }
        void func() {cout << "Base::func() " << endl;}
        virtual void func2(int i) { cout << "Base::func2(int i)" << endl;}
    }; 
    
     
    
    class Derived : public Base
    {  
    public:      
          void func(int i){ cout <<"Derived::func()"<< endl; } 
          void func2(int i){ cout <<"Derived::func2(int i)"<< endl; } 
    }; 
    
    int main()
    {
        Base *pb = new Derived();
        pb->func(1);  //Base::func(int i)
        pb->func();  //Base:func()
        pb->func2(1);  //Derived::func2(int i)
        delete pb; 
    
         Derived *pd = new Derived();
        pd->func(1); //Derived::func(int i)
        // pd->func(); //不能调用 
        pd->func2(1); //Derived::func2(int i)
        delete pd;
    
    }
    View Code
  • 相关阅读:
    页面控制多角度看Model1与Model2
    类型抽象Haxe3新增特性:抽象类型 Abstract Types
    hadoop配置Hadoop 2.0分布式环境搭建安装配置
    PostThreadMessage的应用
    禁用安全模式(2k,2k3,xp)
    如何使用内存池监视器 (Poolmon.exe) 解决内核模式内存泄漏
    WideCharToMultiByte,MultiByteToWideChar
    禁止stMgr.exe
    GetCurrentUserSid
    注册表修改大全
  • 原文地址:https://www.cnblogs.com/cton/p/3536127.html
Copyright © 2020-2023  润新知