0
点赞
收藏
分享

微信扫一扫

c++继承多态虚函数例题

干自闭 2022-01-18 阅读 86
c++oop
  1. 写一个抽象类Pet,里面有3个纯虚函数void setName(string name),string getName();void play();
  2. 写一个类Animal,里面有保护类型的成员变量string name,一个带参数的构造函数,2个成员函数,void walk),void eat()
  3. 写一个类Cat,要求同时继承题2,3中的类。
  4. 写一个类Dog,要求同时继承2,3中的类。
    自己设计编写代码,生成Cat,Dog对象,并且要求体现出多态。
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <string>
using namespace std;
class Pet {
public:
    virtual void setName(string name) = 0;
    virtual string getName() = 0;
    virtual void play()=0;
};
class Animal {
protected:
    string name;
public:
    Animal(string n) :name(n) {}
    void walk() {};
    void eat(){};
};
class Cat :public Pet, Animal {
public:
    Cat() :Animal("Cat") {}
    void setName(string name) {
        name = name;
    }
    string getName(){
        return name;
    }
    void walk() {
        cout << getName() << " is walking" << endl;
    }
    void eat() {
        cout << getName() << " is eating" << endl;
    }
    void play() {
        cout << getName() << " is playing" << endl;
    }
};
class Dog :public Pet, Animal{
public:
    Dog() :Animal("Dog") {}
    void setName(string name) {
        name = name;
    }
    string getName() {
        return name;
    }
    void walk() {
        cout << getName() << " is walking" << endl;
    }
    void eat() {
        cout << getName() << " is eating" << endl;
    }
    void play() {
        cout << getName() << " is playing" << endl;
    }
};
int main()
{
    Dog d;
    Cat c;
    d.walk();
    c.walk();
    d.eat();
    c.eat();
    d.play();
    c.play();
    return 0;
}

在这里插入图片描述

举报

相关推荐

0 条评论