提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目:
定义动物类Animal,具有两个属性:种类和腿条数,并有eat和walk的方法;
定义宠物类Pet继承自动物类,有一个属性:名字,有三个功能:setName、getName和play;
蜘蛛类Spider继承自动物类,重定义eat和walk的方法;
猫类Cat继承自宠物类,重定义eat和walk的方法。
创建一个蜘蛛对象、一个猫对象,设置并输出对象的各项信息,并测试对象的eat和walk方法。
代码:
#include<iostream>
#include<string.h>
using namespace std;
class Animal{
public:
string species;
int number;
Animal(string sp,int num)
{
species=sp;
number=num;
}
void eat()
{
cout<<"食物:吃草," ;
}
void walk()
{
cout<<"行走方式:爬行"<<endl;
}
void print1()
{
cout<<"动物种类:"<<species<<",";
cout<<"腿条数:"<<number<<",";
}
};
class Pet:public Animal{
//private:string name;
public:
string name;
Pet(string sp,int num,string na):Animal(sp,num)
{
name=na;
}
void setname();
void getname();
void play();
};
class Spider:public Animal{
public:
Spider(string sp,int num):Animal(sp,num){}
void eat()
{
cout<<"食物:吃蚊子,";
}
void walk()
{
cout<<"行走方式:爬行"<<endl;
}
void print2()
{
cout<<"蜘蛛种类:"<<species<<",";
cout<<"腿条数:"<<number<<",";
}
};
class Cat:public Pet{
public:
Cat(string sp,int num,string na):Pet(sp,num,na){}
void eat()
{
cout<<"食物:吃猫粮"<<",";
}
void walk()
{
cout<<"行走方式:爬行"<<endl;
}
void print3()
{
cout<<"猫种类:"<<species<<",";
cout<<"名字:"<<name<<",";
cout<<"腿条数:"<<number<<",";
}
};
int main()
{ Spider s1("蜘蛛",8);
s1.print2() ;
s1.eat() ;
s1.walk() ;
Cat c1("猫",4,"旺财");
c1.print3() ;
c1.eat() ;
c1.walk() ;
Cat c2("猫",4,"橘猫");
c2. eat();
cout<<endl;
c2.Pet::eat() ;
return 0;
}
结果:
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了通过编程实现各自的关系并声明自己的属性和方法(C++)。