覆盖:子类对基类的方法进行覆盖,但是能够调用基类的方法,且子类能够添加自己的内容
#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(); //不同动物吃不一样,在各个动物类下,进行方法的重新声明
};
class Turtle:public Animal
{
public:
Turtle(std::string theName);
void swim();
void eat();
};
Animal::Animal(std::string theName)
{
name = theName;
}
void Animal::eat()
{
std::cout<<"基类的吃eating"<<std::endl;
}
void Animal::sleep()
{
std::cout<<"sleeping"<<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;
}
//____________________
Turtle::Turtle(std::string theName):Animal(theName)
{
}
void Turtle::swim()
{
std::cout<<"甲鱼游泳"<<std::endl;
}
void Turtle::eat()
{
Animal::eat();//前面声明过,可直接调用基类的吃
std::cout<<"甲鱼吃东西"<<std::endl;//子类覆盖了基类的方法
}
int main()
{
Pig pig("小猪");
Turtle turtle("甲鱼");
turtle.eat();
pig.climb();
turtle.swim();
pig.eat();
return 0;
}
本文通过C++代码展示了面向对象编程中的子类覆盖基类方法的概念。子类Pig和Turtle继承自Animal类,并重写了eat()方法,同时能够调用基类的eat()方法。在main()函数中,展示了如何实例化这些类并调用它们特有的行为,如Pig的climb()和Turtle的swim(),以及它们各自覆盖后的eat()方法。
1304

被折叠的 条评论
为什么被折叠?



