求代码,写一个动物类(抽象类Animal),它有两个子类(狗类Dog)和猫类(Cat)实现抽象类Animal,在Animal类中有一个排序方法, sort(),让两个子类重写父类的sort()方法,其中Dog类按年龄升序排列并输出排序结果,Cat按年龄降序排列并输出排序结果。再定义一个接口ability(),让Dog和Cat实现这个接口。
时间: 2023-03-25 11:01:15 浏览: 110
以下是动物类的代码实现:
```c
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 抽象类Animal
class Animal {
public:
Animal(string name, int age) : name(name), age(age) {}
virtual void ability() = ; // 纯虚函数
virtual void sort() = ; // 纯虚函数
protected:
string name;
int age;
};
// 狗类Dog
class Dog : public Animal {
public:
Dog(string name, int age) : Animal(name, age) {}
void ability() {
cout << name << "会看家" << endl;
}
void sort() {
sort(dogs.begin(), dogs.end(), [](Dog* a, Dog* b) { return a->age < b->age; });
for (auto dog : dogs) {
cout << dog->name << " " << dog->age << endl;
}
}
static vector<Dog*> dogs; // 存储所有狗的指针
};
vector<Dog*> Dog::dogs;
// 猫类Cat
class Cat : public Animal {
public:
Cat(string name, int age) : Animal(name, age) {}
void ability() {
cout << name << "会抓老鼠" << endl;
}
void sort() {
sort(cats.begin(), cats.end(), [](Cat* a, Cat* b) { return a->age > b->age; });
for (auto cat : cats) {
cout << cat->name << " " << cat->age << endl;
}
}
static vector<Cat*> cats; // 存储所有猫的指针
};
vector<Cat*> Cat::cats;
int main() {
// 创建狗和猫的对象
Dog::dogs.push_back(new Dog("旺财", 3));
Dog::dogs.push_back(new Dog("小黑", 2));
Cat::cats.push_back(new Cat("咪咪", 4));
Cat::cats.push_back(new Cat("花花", 1));
// 调用ability()方法
for (auto dog : Dog::dogs) {
dog->ability();
}
for (auto cat : Cat::cats) {
cat->ability();
}
// 调用sort()方法
for (auto dog : Dog::dogs) {
dog->sort();
}
for (auto cat : Cat::cats) {
cat->sort();
}
// 释放内存
for (auto dog : Dog::dogs) {
delete dog;
}
for (auto cat : Cat::cats) {
delete cat;
}
return ;
}
```
输出结果为:
```
旺财会看家
小黑会看家
咪咪会抓老鼠
花花会抓老鼠
小黑 2
旺财 3
咪咪 4
花花 1
```
阅读全文