C++实现交易存储链表编译报'head未在作用域声明'错误求助
C++链表实现交易商品存储编译错误修复
需求说明
- 编写链表类(含Node节点类和List链表类)存储交易中的商品条目;
- 测试类功能,打印链表中存储的商品条目;
- 展示交易的总价格;
- 从链表中删除一个商品条目后输出新的交易总价格。
输出格式参考如下:BC Items Price 10 Pagoda Gnut 110g 3.49 11 Hup Seng Cream Cracker 4.19 12 Yit Poh 2n1 Kopi-o 7.28 13 Zoelife SN & Seed 5.24 14 Gatsby S/FO Wet&Hard 16.99 15 GB W/G U/Hold 150g 6.49 Total (GST Incl.) 43.68
报错原因
报错[Error] 'head' was not declared in this scope由两个问题共同导致:
head是List类的私有成员变量,类外的main函数没有权限直接访问,无法在main中直接取&head- List类中声明的成员函数
print(Node **head)实现时未加List::作用域限定,变成了全局函数,成员函数声明与实现不匹配
修改步骤
- 调整List类的print函数声明,无需额外传参,成员函数可直接访问私有head
- 修正print函数实现,加上
List::作用域,直接使用类内的head变量 - 调整main函数中的print调用逻辑,不需要传入参数
- 补充缺失的头文件,调整输出格式匹配参考要求
完整可运行代码
#include <iostream> #include <string> #include <iomanip> using namespace std; // Node class class Node { public: double data; string item; Node* next; Node() {}; void setData(double aData) {data = aData; }; void setString(string aItem) {item = aItem;}; void setNext(Node* aNext) {next = aNext; }; double Data() {return data; }; string String() {return item;}; Node* Next() {return next; }; }; // List class class List { Node *head; public: List() { head = NULL; }; void addNode(double data, string item); void total(); void print(); }; //add a node to the list at tail void List::addNode(double n, string m) { Node *newNode = new Node(); newNode->setData(n); newNode->setString(m); newNode->setNext(NULL); // Create a temp pointer Node *tmp = head; if ( tmp != NULL ) { // Nodes already present in the list while ( tmp->Next() != NULL ) { tmp = tmp->Next(); } // Point the last node to the new node tmp->setNext(newNode); } else { // First node in the list head = newNode; } } void List::print(){ Node* a = head; cout << "========================================" <<endl; cout << left << setw(30) << "BC Items" << "Price" <<endl; cout << "========================================" <<endl; while(a){ cout << left << setw(30) << a->item << a->data << endl; a = a->next; } cout << "========================================" <<endl; } void List::total(){ Node* cur = head; double sum=0; cout << left << setw(30) << "Total (GST Incl.)"; while (cur){ sum = sum + cur->data; cur = cur->next; } cout << sum << endl; cout << "========================================" <<endl; } int main() { List list; list.addNode(3.49, "10 Pagoda Gnut 110g"); list.addNode(4.19, "11 Hup Seng Cream Cracker"); list.addNode(7.28, "12 Yit Poh 2n1 Kopi-O"); list.addNode(5.24, "13 Zoelife SN & Seed"); list.addNode(16.99, "14 Gatsby S/FO Wet&Hard"); list.addNode(6.49, "15 GB W/G U/Hold 150g"); list.print(); list.total(); return 0; }
内容的提问来源于stack exchange,提问作者unknown
相关产品推荐
相关产品推荐

