| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1034 人关注过本帖
标题:静态成员变量和类型转换构造函数的题,求帮助
只看楼主 加入收藏
青蝶
Rank: 2
等 级:论坛游民
帖 子:160
专家分:51
注 册:2018-2-4
结帖率:92%
收藏
已结贴  问题点数:20 回复次数:1 
静态成员变量和类型转换构造函数的题,求帮助
代码填空,使得程序能够自动统计当前各种动物的数量,只能在橙色的两句话中间填写代码,红色那一句不知道怎么处理,求大佬看一下。
#include <iostream>
using namespace std;
class Animal{
    public:
        static int number;
};

class Cat{
    public:
        static int number;
        Cat(){
            number++;
            Animal::number++;
        }
        ~Cat(){
            number--;
            Animal::number--;
        }
};

class Dog{
    public:
        static int number;
        Dog(){
            number++;
            Animal::number++;
        }
        ~Dog(){
            number--;
            Animal::number--;
        }
};
            
int Animal::number=0;
int Cat::number=0;
int Dog::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();
}
输入

输出
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
搜索更多相关主题的帖子: int number Cat print the 
2018-09-23 15:36
Jonny0201
Rank: 11Rank: 11Rank: 11Rank: 11
等 级:贵宾
威 望:52
帖 子:488
专家分:2603
注 册:2016-11-7
收藏
得分:20 
程序代码:
#include <iostream>
using namespace std;
class Animal{
    public:
        static int number;
        Animal() {
            ++number;
        }
        virtual ~Animal() {
            --number;
        }
}; 

class Cat : public Animal{
    public:
        static int number;
        Cat(){
            number++;
        }
        ~Cat(){
            number--;
        }
};

class Dog : public Animal {
    public:
        static int number;
        Dog(){
            number++;
        }
        ~Dog(){
            number--;
        }
};
            
int Animal::number=0;
int Cat::number=0;
int Dog::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();
}
2018-09-24 10:44
快速回复:静态成员变量和类型转换构造函数的题,求帮助
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.026306 second(s), 11 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved