C++ 继承后重载

这篇博客探讨了C++中的继承和重载概念。通过`Animal`和`Pig`类的示例,展示了如何在子类`Pig`中覆盖基类`Animal`的`eat`方法,并对它进行重载,增加了新的功能。`Pig`类不仅重写了`eat()`方法,还添加了`climb()`方法,展示了多态性在C++中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承后重载:即先继承,然后再对继承的子类进行重载

#include <iostream>
#include <string>
//吃的参数不同,调用对应的函数
class Animal
{
public:
    Animal(std::string theName);
    void eat();

    void sleep();

private:
    std::string name;
};


class Pig:public Animal
{
public:
    Pig(std::string theName);
    void climb();
    void eat();
    void eat(int eatCount);
};

Animal::Animal(std::string theName)
{
    name = theName;
}

void Animal::eat()
{   
    std::cout<<"(基类)吃(未重载)"<<std::endl;
}


Pig::Pig(std::string theName):Animal(theName)
{

}

void Pig::climb()
{
    std::cout<<"小猪爬树"<<std::endl;
}
void Pig::eat()
{   
    Animal::eat();//基类的吃
    std::cout<<"吃(覆盖基类的吃)"<<std::endl;
}

void Pig::eat(int eatCount)
{   
    std::cout<<"吃(对子类的吃(上面的方法)重载)"<< eatCount <<"碗"<<std::endl;
}

int main()
{
    Pig pig("小猪");
    pig.climb();
    pig.eat();
    pig.eat(15);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alocus_

如果我的内容帮助到你,打赏我吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值