虚函数的各种情况

#include<iostream>
using namespace std;
class Base
{
public:
      virtual void Show()const{cout<<"调用Base::Show()"<<endl;}
};
class Derived:public Base
{
public:
    void Show()const{cout<<"调用Derived::Show()"<<endl;}
};
void Refers1(const Base &obj)
{
    obj.Show();
}
void Refers2(const Base *obj)
{
    obj->Show();
}
int main()
{
    Base obj1;
    Base *p1;
    Derived obj2;
    p1=&obj2;
    obj1=obj2;
    obj1.Show();/*与virtual,引用无关,"调用Base::Show()"。*/
    obj2.Show();/*与virtual无关,"调用Derived::Show()"*/
    Refers2(p1);
    /*1.没有virtual时是不管void Refers1(const Base &obj)中有没有用引用都是"调用Base::Show()",
    2.当有virtual时,没有引用时"调用Base::Show()",有引用"调用Derived::Show()"。*/
    Refers1(obj1);/*与virtual,引用无关,"调用Base::Show()"。*/
    Refers1(obj2);/*1.没有virtual时"调用Base::Show()",有virtual时"调用Derived::Show()"。*/
    return 0;
}

 

posted @ 2012-10-15 15:53  myth_HG  阅读(144)  评论(0编辑  收藏  举报