欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

C++ 类的抽象初练

发布时间:2025/3/15 51 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C++ 类的抽象初练 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
/* 某商店经销一种货物,货物的购进和卖出以箱为单位,各箱的重量不一样, 因此商店需要目前库存的总重量。 现在用c++模拟商店货物购进和卖出的情况*/#include<iostream> using namespace std;//货物类 class Goods{ public:Goods(int w=0){this->weight = w;}int GetW(){return weight;}Goods *next; private://重量int weight; };//商店类 class Shop{ public:Shop(int s=0){this->weights = s;pHead = NULL;}~Shop(){if (pHead!=NULL){Goods *pCurrent = pHead;Goods *pNext = NULL;while (pCurrent){pNext = pCurrent->next;delete pCurrent;pCurrent = NULL;pCurrent = pNext;}}weights = 0;}//卖出void SellOut(){if (pHead==NULL){cout << "商店里已经没有货物了!" << endl;}else{//队列 先进先出Goods *pCurrent = pHead;pHead = pHead->next;delete pCurrent;}}//购进void Purchase(Goods *&pin){if (pHead==NULL){//插入第一箱货物pHead = pin;weights += pin->GetW();}else{Goods *pCurrent = pHead;while (pCurrent->next){pCurrent = pCurrent->next;}pCurrent->next = pin;weights += pin->GetW();}}//查询货物重量int GetWeight(){return weights;} private:int weights;Goods *pHead; };void protectA(){Shop *sp = new Shop();int indexover = 1;while (indexover){int num = 0;int w = 0;cout << "请输入操作:" << endl;cout << "1购进货物" << endl;cout << "2卖出货物" << endl;cout << "3查看现有货物重量" << endl;cout << "按任意键退出" << endl;cin >> num;switch (num){case 1:cout << "请输入货物的重量" << endl;//备注:在c++中不可以在case语句里定义任意变量,如果非要定义,请外面套上大括号{}//int ss = 0;//报错 : error C2360: “ss”的初始化操作由“case”标签跳过 {cin >> w;Goods * g1 = new Goods(w);sp->Purchase(g1);}break;case 2:{sp->SellOut();}break;case 3:cout << "现有货物的重量是" << sp->GetWeight() << endl;break;default:indexover = 0;break;}}if (sp!=NULL){delete sp;} } void main(){protectA();system("pause"); }

 

转载于:https://www.cnblogs.com/zhanggaofeng/p/5612562.html

总结

以上是生活随笔为你收集整理的C++ 类的抽象初练的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。