某商店经销一种货物,货物成箱购进,成箱卖出,购进和卖出时以重量为单位,各箱的重量不一样,

某商店经销一种货物,货物成箱购进,成箱卖出,购进和卖出时以重量为单位,各箱的重量不一样,因此,商店需要记录下目前库存的货物的总重量,现在要求设计一个Goods类并使用静态成员来模拟商店货物购进和卖出的情况:Goods类有一个int型weight成员数据(表示本箱货物的重量,每个Goods对象的weight值不同,一个Goods对象表示一箱货物);有一个int型totalWeight静态成员变量,记录所有Goods对象的weight值之和;有一个int GetTotalWeight()静态成员函数,返回totalWeight的值;有一个Goods(int w)构造函数,初始化weight的值,并将totalWeight的值增加weight,注意:创建一个Goods对象就是买入一箱货物(因为要调用此构造函数);有一个void Sell()成员函数,用于将weight赋值为0(表示卖出);。实现以上要求,创建多个Goods对象、卖出等操作并测试通过。然后为上面的Goods类添加一个常数据成员(货物名称),并对货物名称进行初始化;最后将前面已定义的某些成员函数改写为常成员函数,观察是否该类中所有的成员函数是否都可设定为常成员函数。

第1个回答  2014-04-07
#include <iostream>

using namespace std;

class Goods
{
private:
    int weight;
    static int totalWeight;
public:
    Goods(int w);
    static int GetTotalWeight();
    void sell();
};

int Goods::totalWeight = 0;

Goods::Goods(int w)
{
    this->weight = w;
    totalWeight += w;
}

int Goods::GetTotalWeight()
{
    return Goods::totalWeight;
}

void Goods::sell()
{
    Goods::totalWeight -= this->weight;
    this->weight  = 0;
}

int main()
{
    Goods goods1(100);
    cout<<Goods::GetTotalWeight()<<endl;
    goods1.sell();
    cout<<Goods::GetTotalWeight()<<endl;
    return 0;
}

相似回答