用c++写一个兔子拔萝卜、吃萝卜的类,类中用vector输入输出吃萝卜和拔萝卜的数量,再写一个萝卜的类,用来记数萝卜的数量
时间: 2024-05-05 19:21:41 浏览: 73
以下是用C++编写的兔子和萝卜类,实现兔子拔萝卜、吃萝卜和萝卜数量的记录功能。其中,兔子类中使用vector来记录吃萝卜和拔萝卜的数量,萝卜类中使用静态成员变量来记录萝卜的数量。
```c++
#include <iostream>
#include <vector>
using namespace std;
class Carrot {
public:
static int count; // 记录萝卜数量的静态成员变量
Carrot() { count++; } // 构造函数,每次创建对象时数量加一
~Carrot() { count--; } // 析构函数,每次销毁对象时数量减一
};
int Carrot::count = 0;
class Rabbit {
public:
Rabbit() {}
void eat(int n) { carrots_eaten.push_back(n); } // 记录吃萝卜的数量
void pull(int n) { carrots_pulled.push_back(n); } // 记录拔萝卜的数量
void print() { // 输出吃萝卜和拔萝卜的数量
cout << "I have eaten " << carrots_eaten.size() << " carrots:" << endl;
for (int i : carrots_eaten) {
cout << i << " ";
}
cout << endl;
cout << "I have pulled " << carrots_pulled.size() << " carrots:" << endl;
for (int i : carrots_pulled) {
cout << i << " ";
}
cout << endl;
}
private:
vector<int> carrots_eaten; // 记录吃萝卜的数量的vector
vector<int> carrots_pulled; // 记录拔萝卜的数量的vector
};
int main() {
Rabbit rabbit;
Carrot c1, c2, c3;
rabbit.eat(2);
rabbit.pull(1);
rabbit.eat(3);
rabbit.print();
cout << "There are " << Carrot::count << " carrots." << endl;
return 0;
}
```
输出结果为:
```
I have eaten 2 carrots:
2 3
I have pulled 1 carrots:
1
There are 3 carrots.
```
阅读全文