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

296 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

动物类例题

  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;
}

效果如下: 在这里插入图片描述

纯虚函数和抽象类 实现shape类

在这里插入图片描述

#include <iostream>
using namespace std;
const double PI = 3.1415926;
class Shape
{
public:
	virtual double getArea() const = 0;
	Shape() {}
	~Shape() {}
};
class Rectangle :public Shape {
public:
	Rectangle() { length = 0.0; width = 0.0; }
	~Rectangle() {}
	Rectangle(double length, double width) :length(length), width(width) {}
	virtual double getArea() const{
		return length * width;
	}
private:
	double length, width;
};

class Circle :public Shape {
public:
	Circle() { radius = 0.0; }
	Circle(double radius) :radius(radius) {}
	~Circle() {}
	virtual double getArea() const{
		return radius * PI * radius;
	}
private:
	double radius;
};
class Total {
public:
	Total(Shape* shape1, Shape* shape2) :shape1(shape1), shape2(shape2) {}
	double sumArea() {
		return shape1->getArea() + shape2->getArea();
	}
private:
	Shape* shape1;
	Shape* shape2;
};
int main()
{
	Rectangle r(3.0 ,2.0);
	Circle c(1.0);
	Total t(&r, &c);

    std::cout << t.sumArea();

}