实训c++程序第三天

一木 889 0

第一个程序:

c++建立基类指针指向继承类

问题描述:使用虚函数完成下面的问题,要求:
1. 建立基类 animal,方法有 sleep(输出“animal is sleeping”)
2. 建立鱼类继承 fish,覆盖 sleep 方法(输出“fish is not sleeping”)
3. 建立基类的指针 p,指向 fish,最后输出“fish is not sleeping”

运行的结果是fish is not sleeping  实现是是函数覆盖。如果基类中不加virtual  则只输出animal is sleeping

参考:https://blog.csdn.net/u010711820/article/details/54616984

 

#include<iostream>
#include<string>
using namespace std;
class animal
{
    public:
        virtual void sleep(){
            cout<<"animal is sleeping"<<endl;
            }
    };

    class fish:public animal
    {
        public:
        void sleep(){
            cout<<"fish is not sleeping"<<endl;
            }
        };
    int main(){
        animal* p;
        p=new fish;
        p->sleep();
        }

第二个程序:

对于类的建立

宠物类:

class pet//宠物类
    {
    public:
    pet(int a=0,int h=0,int t=0,int m=0,int he=0,int s=20)
	{
		age=a;
		hunger=h;
		thirst=t;
		mood=m;
		health=he;
		step=s;
	}
    int getAge(){return age;}
	int getHunger(){return hunger;}
	int getThirst(){return thirst;}
	int getMood(){return mood;}
	int getHealth(){return health;}
	int getStep(){return step;}
	void p2();//饥饿,口渴,及心情随时间变化的函数;
	void show();//显示宠物的基本信息
    void emergency(int w);//各种特殊状态的显示
    void feed()//喂食函数
	{
		hunger--;
		step=step-5;
	}
   void drink()//喂水函数
	{
		thirst--;
		step=step-3;
	}
	void doctor()//看医生
	{
	    step=step-10;
	    health++;
	    }
	void touch(int w);//抚摸函数
	void fun(int w);//玩耍函数
	virtual int getl()//提取寿命值,virtual是重写,因为各个动物返回的值不一样
	{
		return age;
	}
    virtual void action(int act,int w,int emg)//主人的行为函数
    {

        }



    private:
        int age;//年龄
        int hunger;//饥饿值
        int thirst;//口渴值
        int mood;//心情值
        int health;//健康值
        int step;//行动值


    };

兔子类:

    //兔子类
    class rabbit:virtual public pet
    {
    public:
        rabbit(int l=31){
            life=l;
            }
        int getl()
        {
            return life;
            }
        void action(int act,int w,int emg);//对兔子做的动作
    private:
        int life;//兔子的寿命
    };

小马驹类:

 //马类
    class horse:virtual public pet
    {
        public:
        horse(int l=41){
            life=l;
            }
        int getl(){
            return life;
            }
        void action(int act,int w,int emg);//对马做的动作
    private:
        int life;//马的寿命
        };

小牛牛类:

        //牛类
    class cow:virtual public pet
    {
           public:
        cow(int l=51){
            life=l;
            }
        int getl(){
            return life;
            }
        void action(int act,int w,int emg);//对牛做的动作
    private:
        int life;//牛的寿命
         };

发表评论 取消回复
表情 图片 链接 代码

分享