【转】父类子类指针相互转换问题

1.当自己的类指针指向自己类的对象时,无论调用的是虚函数还是实函数,其调用的都是自己的;

2.当指向父类对象的父类指针被强制转换成子类指针时候,子类指针调用函数时,只有非重写函数是自己的,虚函数是父类的;

3.当指向子类对象的子类指针被强制转换成父类指针的时候,也就是父类指针指向子类对象,此时,父类指针调用的虚函数都是子类的,而非虚函数都是自己的。

将上面三句话总结成一句话就是:当父类子类有同名非虚函数的时候,调用的是转换后的指针类型的函数;

              当父类子类有同名虚函数的时候呢,调用的是指针转换前指向的对象类型的函数。

详见以下代码:

#include <iostream>

using namespace std;

class Base
{
public:
    virtual void f(){cout<<"Base::f"<<endl;}
    virtual void g(){cout<<"Base::g"<<endl;}
    void h(){cout<<"Base::h"<<endl;}
};

class Derived:public Base
{
public:
    virtual void f(){cout<<"Derived::f"<<endl;}
    virtual void g(){cout<<"Derived::g"<<endl;}
    void h(){cout<<"Derived::h"<<endl;}
};

int main()
{
    Base* pB=new Base();
    cout<<"当基类指针指向基类对象时:"<<endl;
    pB->f();
    pB->g();
    pB->h();
    cout<<endl;
    
    Derived *pD=(Derived*)pB;
    cout<<"当父类指针被强制转换成子类指针时:"<<endl;
    pD->f();
    pD->g();
    pD->h();
    cout<<endl;

    Derived *pd=new Derived();
    cout<<"当子类指针指向子类时候"<<endl;
    pd->f();
    pd->g();
    pd->h();
    cout<<endl;

    Base *pb=(Base *)pd;
    cout<<"当子类指针被强制转换成父类指针时:"<<endl;
    pb->f();
    pb->g();
    pb->h();
    cout<<endl;

    Base *pp=new Derived();
    cout<<"父类指针指向子类对象时候:"<<endl;
    pp->f();
    pp->g();
    pp->h();
    cout<<endl;

}

执行结果如下图:

转自:http://www.cnblogs.com/mu-tou-man/p/3925433.html

原文地址:https://www.cnblogs.com/codingmengmeng/p/7282627.html