6-2 模拟水果的进货和出货【武汉理工大学】

构造一个水果类,模拟水果的进货和出货过程,正确反映目前水果总重量和总数量的变化。要求给出水果类的类外实现。

裁判测试程序样例:

#include <iostream>
using namespace std;
class CFruit{
float weight;  //每箱水果的重量
static float total_weight; //水果的总重量
static int total_number; //水果的总数量
public:
  CFruit(float w) ;     //模拟进货
  CFruit(CFruit &f) ;   //模拟进货
  ~CFruit();          //模拟出货
  static void total_display() //显示目前水果的总重量和总数量
  { cout<<"Total weight is:"<<total_weight<<endl;
    cout<<"Total number is:"<<total_number<<endl; }
};

int main()
{    
    float a,b;
    cin>>a>>b;
    CFruit f1(12.5);  //进货f1
    CFruit::total_display();  
    CFruit f2(f1);  //进货f2
    CFruit::total_display();
    CFruit f3(10.5);  //进货f3
    CFruit::total_display();
    f2.~CFruit();      //出货
    CFruit::total_display();
    return 0}

输入样例:

12.5

10.5

输出样例:

Total weight is:12.5

Total number is:1

Total weight is:25

Total number is:2

Total weight is:35.5

Total number is:3

Total weight is:23

Total number is:2
/ 静态成员变量的初始化
float CFruit::total_weight = 0;
int CFruit::total_number = 0;

float CFruit::total_weight = 0;
int CFruit::total_number = 0;

// 构造函数,模拟进货
CFruit::CFruit(float w) : weight(w) {
    total_weight += weight;
    total_number++;
}

// 复制构造函数,模拟进货
CFruit::CFruit(CFruit &f) : weight(f.weight) {
    total_weight += weight;
    total_number++;
}

// 析构函数,模拟出货
CFruit::~CFruit() {
    total_weight -= weight;
    total_number--;
}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值