【发布时间】:2018-12-09 04:50:11
【问题描述】:
我正在编写一些简单的 C++ 管理程序,它有一个仓库类,其中包含一个存储为链接列表的产品列表。 输出有两个问题:
- 输出 id/s 与输入不同(但也相似)
- 有两种不同的打印功能,但在运行程序时只执行一个(如果我注释了另一个,它们都可以运行)
由于程序编译没有任何错误,我尝试逐行调试,但似乎无法弄清楚
编辑:为了明确大学项目的这一部分,我不能使用标准库中准备好的东西,比如 (std::vector, std::list, ...) 我需要手动实现链表
#include <iostream>
#include <iomanip> // std::setw
struct product {
int id;
int num;
product* next;
};
class warehouse{
private:
product* list = new product;
public:
warehouse() = default;
//adding a product to warehouse
void AddProduct(const int id,const int boxes) {
auto* item = new product;
auto* tmp = new product;
// copy the head of the linked list
tmp = list;
item->id = id;
item->num = boxes;
item->next = tmp;
//add the the new product at the beginning
list = item;
}
//print all products
void printlist() {
int i=0;
product* tmp;
tmp = list;
while(list) {
i++;
std::cout << "item n." << i << "\tid: " << tmp->id << " number of items: " << tmp->num << std::endl;
tmp = tmp -> next;
}
}
//print products that have less than 50 box and need resupply
void SupplyReport(){
product* tmp = new product;
tmp = list;
int i=0;
while(list) {
if (tmp->num <= 50) {
i++;
std::cout << i << ". id:" << tmp->id << std::setw(20) << "N. of Boxes:" << tmp->num << std::endl;
}
tmp = tmp -> next;
}
if (i==0)
std::cout << "No product/s need re-supply";
}
};
int main(){
/* Problems:
* Generating random id instead of using the given values
* Execute only one function at a time meaning if I commented printlist it's print the supply report as expected
*/
warehouse w1;
w1.AddProduct(005,50);
w1.AddProduct(007,70);
w1.AddProduct(055,30);
w1.printlist();
w1.SupplyReport();
return 0;
}
【问题讨论】:
-
注意 C++ 已经有一个你可能想要使用的链表
std::list -
@MartinYork 不幸的是,这是大学项目的一部分,我不能使用从 std 准备好的东西,我需要手动实现它们
-
这对大学来说是完全合理的。值得注意的是问题的一部分。
标签: c++ class linked-list octal