- 写一个抽象类Pet,里面有3个纯虚函数void setName(string name),string getName();void play();
- 写一个类Animal,里面有保护类型的成员变量string name,一个带参数的构造函数,2个成员函数,void walk),void eat()
- 写一个类Cat,要求同时继承题2,3中的类。
- 写一个类Dog,要求同时继承2,3中的类。
自己设计编写代码,生成Cat,Dog对象,并且要求体现出多态。
#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;
}