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

  • 当父类子类有同名非虚函数的时候,调用的是转换后的指针类型的函数;

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

#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;}
            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;
}

在这里插入图片描述
转载于——父类子类指针相互转换问题

猜你喜欢

转载自blog.csdn.net/weixin_48622537/article/details/111821440