总时间限制:
1000ms
内存限制:
65536kB
描述
代码填空,使得程序能够自动统计当前各种动物的数量
- #include
- using namespace std;
- // 在此处补充你的代码
-
- void print() {
- cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
- }
-
- int main() {
- print();
- Dog d1, d2;
- Cat c1;
- print();
- Dog* d3 = new Dog();
- Animal* c2 = new Cat;
- Cat* c3 = new Cat;
- print();
- delete c3;
- delete c2;
- delete d3;
- print();
- }
输入
无
输出
0 animals in the zoo, 0 of them are dogs, 0 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats
6 animals in the zoo, 3 of them are dogs, 3 of them are cats
3 animals in the zoo, 2 of them are dogs, 1 of them are cats
样例输入
None
样例输出
0 animals in the zoo, 0 of them are dogs, 0 of them are cats 3 animals in the zoo, 2 of them are dogs, 1 of them are cats 6 animals in the zoo, 3 of them are dogs, 3 of them are cats 3 animals in the zoo, 2 of them are dogs, 1 of them are cats
看到了main函数里面的Dog,Cat,Animals这3个类,就已经明确了我们类的名称了,在print函数中,也确认了每一个类中的成员变量.
看一下输出,翻译成中文是有0只动物,0只狗,0只猫,还有题目,就知道我们还需要统计这些动物的数量,怎么统计呢?当然是在成员变量number里面计数,但是在main函数中一直没有出现计数的函数,所以只能写在创建对象时自动运行的构造函数里面.
在Cat和Dag的构造函数中,我们首先要将自己这个类里面你number+1,但是怎么加Animals类中的number呢?所以说,我们可以将Animals写成一个基类,Cat和Dog是它的派生类,但是由于Animals类中的number和他派生出来的类里面的成员变量重名了,改名字行不行呢?不行,因为print已经规定了我们的名称.
所以想要在Dog和Cat的构造函数中使用Animlas的number只有特殊声明一下,在前面加上Animlas::就可以了.
然后我们发现,在main中还有delete这个删除操作,我们得写析构函数了,怎么写,之前是将自己类的numbe++,和Animals的number++,现在则正好相反,直接--.
因为想写派生类的构造函数,必须先执行基类的构造函数,而我们的各种操作已经在派生类的构造函数中完成了,所以我们只需要写一个空的构造函数,但是要在前面加上关键字,表示是一个虚函数.
最后还有一个需要注意的事情,我们的numbe必须要是静态成员变量,为什么呢?因为只有叫静态成员变量是所有类共有的.
但是需要注意的是静态成员变量需要在类外单独分配空间,编译就行不通.
- #include
- using namespace std;
- class Animal{
- public:
- static int number;
- virtual ~Animal(){
-
- }
- };
- class Dog:public Animal{
- public:
- static int number;
- Dog(){
- number++;
- Animal::number++;
- }
- ~Dog(){
- number--;
- Animal::number--;
- }
- };
- class Cat:public Animal{
- public:
- static int number;
- Cat(){
- number++;
- Animal::number++;
- }
- ~Cat(){
- number--;
- Animal::number--;
- }
- };
- int Animal::number = 0, Dog::number = 0, Cat::number = 0;
- void print() {
- cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
- }
- int main() {
- print();
- Dog d1, d2;
- Cat c1;
- print();
- Dog* d3 = new Dog();
- Animal* c2 = new Cat;
- Cat* c3 = new Cat;
- print();
- delete c3;
- delete c2;
- delete d3;
- print();
- }
因为这是关于多态这个章节的最后一题,所以我讲的非常详细,之后我会发一个关于C++多态的程序学习总结!