C++父类和子类的关系以及指针和引用在派生中起到的作用

#include<iostream>
using namespace std;

class Base
{
public:
    void Method1()
    {
        cout << "This is Base's method1." << endl;
    }
    virtual void Method2()
    {
        cout << "This is Base's method2." << endl;
    }
};

class Derive :public Base
{
public:
    void Method1()
    {
        cout << "This is Derive's method1." << endl;
    }
    void Method2()
    {
        cout << "This is Derive's method2." << endl;
    }
public:
    int m_num;
};

int main()
{
    Base b;
    b.Method1();

    Derive d;
    d.Method1();

    Base *p1 = &d;
    p1->Method1();//调用的是Base类中的方法

    //Derive *p2 = &b;//编译报错,派生类无法引用其父类

    //int num = p1->m_num;//编译报错,父类无法引用子类的数据成员

    Base &q1 = d;
    q1.Method1();//调用的是Base类中的方法

    Base &q2 = d;
    q2.Method2();//调用的是Derive类中的方法

    Base b1 = d;//将调用拷贝构造函数
    b1.Method2();//调用的是Base类中的方法

    //Derive d1 = (Derive)b;//编译报错,无法将父类对象强制转换成子类

    /*
    结论:
        ①指针和引用本质上意义相同,所以在多态性上体现的功能是一致的;
        ②C++中,子类对象可以转换为父类型,而无法将父类对象强制转换为子类型;
        ③父类指针或引用无法访问子类新增的数据成员;
    */

    system("pause");
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值