猫类的定义

文章介绍了如何在C++中声明一个Cat类,包含静态数据成员HowManyCats用于记录猫的数量,以及静态成员函数GetHowMany进行访问。构造函数接受年龄参数,析构函数用于数量减一。还展示了如何在creating函数中动态创建和销毁猫对象,以及在主程序中展示静态数据的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

【问题描述】声明一个Cat类,使其至少满足以下要求:

(1)拥有静态数据成员HowManyCats,记录Cat的个体数目。

(2)声明静态成员函数GetHowMany(),存取HowManyCats。

(3)能够以年龄作为构造函数参数,建立合理的构造函数

(4)能够合理实现程序中猫数量的增减。

(5)设计一个名为creating()的函数,该函数的主要功能为创建一个含有5个指向猫对象的指针数组,用于动态创建5个猫对象,猫的年龄分别为1,2,3,4,5。并显示数组创建前后情况下猫的数量。函数参数自拟。

(6)能够合理创建主程序,该主程序能够在调用函数creating()前后显示猫的数量,在体会静态数据成员和静态成员函数的用法。

【输入形式】该程序无输入,请仔细观察输出

【输出形式】输出结果如下图;

before the function,the number of the cat is:0

before the Cat array is created,the number of the cat is:0

after the Cat array is created,the number of the cat is:5

destructing of the cat!

destructing of the cat!

destructing of the cat!

destructing of the cat!

destructing of the cat!

after the function,the number of the cat is:0


解题思路

        根据题意分别在类中定义静态变量和默认变量即可,含构造函数以及析构函数的使用


源代码

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

class Cat {
    int age;
    static int HowManyCats;
public:
    Cat(int a = 0) : age(a) {
        HowManyCats++;
    }
    ~Cat() {
        HowManyCats--;
        cout << "destructing of the cat!" << endl;
    }
    static int GetHowMany() {
        return HowManyCats;
    }
};

int Cat::HowManyCats = 0;

void creating() {
    cout << "before the Cat array is created,the number of the cat is:" << Cat::GetHowMany() << endl;
    Cat* pts[5];
    for (int i = 0; i < 5; i++) {
        pts[i] = new Cat(i + 1);
    }
    cout << "after the Cat array is created,the number of the cat is:" << Cat::GetHowMany() << endl;
    for (int i = 0; i < 5; i++) {
        delete pts[i];
    }
}

int main() {
    cout << "before the function,the number of the cat is:" << Cat::GetHowMany() << endl;
    creating();
    cout << "after the function,the number of the cat is:" << Cat::GetHowMany() << endl;
    return 0;
}

总结

        这里注意在main函数外的函数里面定义类,以及静态变量的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想我记得写信

您的鼓励是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值