具有链表特性的类
买卖货物问题: #include <iostream> using namespace std; class Goods{ public: Goods(){ m_pNext = nullptr; m_weight = 0; cout << "买入了货物,重量是:" << m_weight << endl; } Goods(int weight){ m_pNext = nullptr; m_weight = weight; total_weight += m_weight; cout << "买入了货物,重量是:" << m_weight << endl; } ~Goods(){ total_weight -= m_weight; // m_pNext 不是在本类中 new 的,所以也不用 delete this->m_pNext = nullptr; cout << "卖出了货物,重量是:" << m_weight << endl; } static int getTotalWeight(){ return total_weight; } Goods *m_pNext; private: int m_weight; static int total_weight; }; int Goods::total_weight = 0; void buy(Goods *&head, int weight){ Goods *pNewGoods = new Goods(weight); if(head == nullptr){ head = pNewGoods; } else{ pNewGoods->m_pNext = head; head = pNewGoods; } } void sale(Goods *&head){ if(head == nullptr){ cout << "没有货物了" << endl; return; } Goods *temp = head; head = head->m_pNext; delete temp; temp = nullptr; } int main( ) { Goods *head = nullptr; int choice; do{ // 提供菜单 cout << "输入 1 进货" << endl; cout << "输入 2 出货" << endl; cout << "输入 0 退出" << endl; cin >> choice; switch(choice){ case 0: // 退出 return 0; case 1: { // 进货 int w = 0; cout << "输入货物重量:" << endl; cin >> w; buy(head, w); break; } case 2: // 出货 sale(head); break; } cout << "目前货物的总重量是:" << Goods::getTotalWeight() << endl; }while(1); return 0; } 输出:...