关于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继承函数的调用
//如果对于父类函数(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、非virtual继承函数的调用
//对于父类函数(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),如果有同型函数:
//----非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

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

上一篇:hdu 4031 Attack(树状数组)


下一篇:【wikioi】借教室