日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

C++ 类的抽象初练

發布時間:2025/3/15 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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++ 类的抽象初练的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。