c++ 类继承和多态

#include <iostream>
using namespace std;
class people
{
public:
    //people()
    //{
    //    cout<<"人类构造函数";
    //}
    people(int weight,int height)
    {
        //带参数
    }
    ~people()
    {

    }
    void eat()
    {
        cout<<"人类吃的方法"<<endl;
    }
    //void breathe()
    //{
    //    cout<<"人类呼吸方法"<<endl;
    //}
    virtual void breathe()
    {
        cout<<"人类的呼吸方法"<<endl;
    }
    protected:
    void sleep()
    {
        cout<<"人类睡觉方法"<<endl;
    }

    //受保护的 外部不能访问,但是子类可以访问
    
};
//定义一个鱼类 与人类有同样的方法 可以直接从人类继承过来
//class fish
//{
//    void eat()
//    {
//    }
//    void sleep()
//    {
//    }
//    void breathe()
//    {
//
//    }
//};
class fish:public people
{
public:
    //基类构造函数有参数 采用这种方面传递参数给基类
    //给常量赋值,常量要初始化
    fish():people(400,300),a(1)
    {
        cout<<"鱼的构造函数"<<endl;
    }
    ~fish()
    {

    }
    //void test()
    //{
    //    breathe();
    //    //可以访问父类 受保护的方法
    //}
    //函数覆盖 存在父类和子类中
    void breathe()
    {
        //people::breathe();
        cout<<"鱼类的呼吸方法"<<endl;
        //cout<<"覆盖父类的方法"<<endl;
    }
    
private:
        const int a; //声明一个常量
};
//people 是父类或者基类

void fn(people *pin)
{
    pin->breathe();
}
void main()
{
    people p(4,3);
    p.eat();
    fish  f;
    people *pin;
    pin=&f;
    fn(pin);
    //调用的是人类呼吸的方法
    //如果想调用鱼类的呼吸方法 ,要把人类类的呼吸函数 改成虚函数
    //f.sleep();
    //f.test();
    //f.breathe();
}
//如果基类有虚函数 传递子类指针 子类有的调用子类,子类没有的调用父类,c++多态性
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值