zoukankan      html  css  js  c++  java
  • 关于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
  • 相关阅读:
    Nginx服务器环境搭建
    PostgreSQL常见问题处理方法
    Linux之awk使用
    PostgreSQL常用SQL
    用apache commons-pool2建立thrift连接池
    redis开发小结
    如何解决netty发送消息截断问题
    后端服务开发总结
    利用git reflog找回错误的重置
    TCP长链接调试利器nc
  • 原文地址:https://www.cnblogs.com/cton/p/3536127.html
Copyright © 2011-2022 走看看