用c++写一个类Animal, 并对其成员变量name和age使用构造函数进行赋值,Animal类包含3个变量t1, t2 和t3, t1,t2和t3都有name和age, age表示t1,t2,t3的年龄,age 为int 类型,name为string类型,并对t1, t2和t3的age进行排序
时间: 2024-02-03 19:13:39 浏览: 28
以下是使用C++编写的Animal类,其中包含t1, t2, t3三个对象,每个对象都有name和age两个成员变量。使用构造函数对t1, t2和t3的name和age进行赋值,使用sort函数对t1, t2和t3的age进行排序。
```C++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class Animal {
public:
string name;
int age;
Animal(string n, int a) {
name = n;
age = a;
}
};
bool cmp(Animal a, Animal b) {
return a.age < b.age;
}
int main() {
Animal t1("Tom", 5);
Animal t2("Jerry", 3);
Animal t3("Spike", 7);
Animal animals[] = {t1, t2, t3};
sort(animals, animals+3, cmp);
for (int i = 0; i < 3; i++) {
cout << animals[i].name << " " << animals[i].age << endl;
}
return 0;
}
```
输出结果为:
```
Jerry 3
Tom 5
Spike 7
```