某商店经销一种货物。货物购进和卖出时以箱为单位,各箱的重量不一样,因此,商店需要记录目前库存的总重量。现在用C++模拟商店货物购进和卖出的情况。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| #include<iostream> using namespace std; class Goods { private: int weight; static int total_weight; public: Goods *pNext; Goods(int weight) { this->weight = weight; total_weight += weight; } ~Goods() { total_weight -= weight; } int GetWeight() { return weight; } static int GetTotalWeight() { return total_weight; } }; int Goods::total_weight = 0; void menu() { cout << "============================" << endl; cout << " 商店货物系统" << endl; cout << " 输入1购进" << endl; cout << " 输入2卖出" << endl; cout << " 输入0退出" << endl; cout << "============================" << endl; }
void Purchase(Goods * &Head, Goods * &Tail,int weight) { Goods *pNew = new Goods(weight); pNew->pNext = NULL; if (Head == NULL && Tail == NULL) { Head = Tail = pNew; } else { Tail->pNext = pNew; Tail = pNew; } } void Sale(Goods * &Head) { if (Head == NULL) { cout << "没有货物!" << endl; return; } Goods *Temp = Head->pNext; delete Head; Head = Temp; } int main() { Goods *Head = NULL; Goods *Tail = NULL; int choice = -1; int weight = 0; do { menu(); cin >> choice; switch (choice) { case 1: { cout << "请输入重量:"; cin >> weight; Purchase(Head, Tail, weight); break; } case 2: { Sale(Head); break; } case 0:exit(0); break; default:cout << "输入错误,请重新输入!" << endl; break; } cout << "总重量为:" << Goods::GetTotalWeight() << endl << endl; } while (1); return 0; }
|