构造一个水果类,模拟水果的进货和出货过程,正确反映目前水果总重量和总数量的变化。要求给出水果类的类外实现。
裁判测试程序样例:
#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--;
}
}