c++ 链表和类配合使用
Goods类,用于存放每件货物重量,total_weight用来存储全部重量 ,通过三个函数实现,对链表的增删遍历
#include <iostream>
using namespace std;
class Goods
{
public:
Goods()
{
m_weight = 0;
m_next = NULL;
}
Goods(int weight)
{
this->m_weight = weight;
m_next = NULL;
total_weight += weight;
cout<<"当前添加重量为:"<<this->m_weight<<"总重量为:"<<total_weight<<endl;
}
int get_mweight()
{
return this->m_weight;
}
~Goods()
{
cout<<"已删除"<<endl;
total_weight -= this->m_weight;
}
Goods* m_next;
private:
int m_weight;
static int total_weight;
};
int Goods::total_weight = 0;
void buy(Goods*& head,int weight)
{
Goods* temp = new Goods(weight);
if(head == NULL)
{
head = temp;
}
else
{
temp->m_next = head;
head = temp;
}
}
void sale(Goods*& head)
{
if(head == NULL)
{
cout<<"没有可以删除的节点"<<endl;
}
else
{
Goods* temp = head->m_next;
delete head;
head = temp;
}
}
void Goods_display(Goods* head)
{
if(head == NULL)
cout<<"没有货物"<<endl;
while(head != NULL)
{
cout<<head->get_mweight()<<endl;
head = head->m_next;
}
}
int main(void)
{
int choise = 0;
Goods* head = NULL;
int weight = 0;
while(1)
{
cout<<"1、进货"<<endl;
cout<<"2、出货"<<endl;
cout<<"3、遍历"<<endl;
cout<<"0、退出"<<endl;
cin>>choise;
switch (choise)
{
case 1:
cout<<"请输入货物重量:"<<endl;
cin>>weight;
buy(head,weight);
break;
case 2:
sale(head);
break;
case 3:
Goods_display(head);
break;
case 0:
exit(0);
break;
default:
break;
}
}
return 0;
}
- 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
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
推荐阅读