2.把程序运行结果截图粘贴在下方。(因语法错误不能生成可执行文件的,无运行结果,不粘贴截
图)
3.把完成的源代码插入到下方。
#include<iostream>
#include<string>
using namespace std;
//货物名称(string类型)、单价、数量
class Item
{
friend class Cart;
private:
string itemname;
double price;
int num;
Item* next;//Item类中包含一个指向下一个货物对象的指针
public:
//构造函数
Item(string item, double pri, int n)
:itemname(item),
price(pri),
num(n),
next(nullptr)
{ }
//复制构造函数,使用深度拷贝
Item(const Item& I)
{
this->itemname = I.itemname;
this->num = I.num;
this->price = I.price;
}
void InitItem(string item, double pri, int n)
{
itemname = item;
price = pri;
num = n;
next = nullptr;
}
//访问成员变量的成员函数
double GetPrice()
{
return price;
}
double GetNum()
{
return num;
}
void ShowItem()
{
cout <<itemname << " " << price << " " << num;
}
};
// 购物车类
class Cart {
private:
struct Node {
Item item;
Node* next;
Node(Item& item) : item(item), next(nullptr) {}
};
Node* head;
Node* current;
public:
Cart()
: head(nullptr),
current(nullptr)
{}
//复制构造函数(请使用深拷贝)
Cart(const Cart& C)
{
this->current->item.itemname = C.current->item.itemname;
this->current->item.num = C.current->item.num;
this->current->item.price = C.current->item.price;
}
void InitItem(Item& item)
{
head = new Node(item);
current = head;
}
void addItem(Item& item)
{
current->next = new Node(item);
current = current->next;
}
//向购物车中添加货物
void Changenum(string item, double pri, int n)
{
Node* p = head;
while (p != nullptr)
{
if (p->item.itemname == item)
{
p->item.num=n;
break;
}
}
if (p == nullptr)
{
Item it(item, pri,n);
addItem(it);
}
}
void displayCart()
{
Node* p = head;
double sum = 0;
double each = 0;
while (p != current->next) {
each = p->item.GetNum() * p->item.GetPrice();
cout << p->item.itemname << " " << p->item.price << " " << p->item.num<< " " << each<<endl;
sum += each;
p = p->next;
}
cout << "Total : " << sum;
cout << endl;
}
//析构函数
~Cart() {
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
};
int main() {
cout << "Never ending" << endl;
cout << "-------------------------------------------" << endl;
Item item1("Pen", 3.99, 3);
Item item2("Mug", 17.99, 1);
Cart cart;
cout << "商品名称 " << "商品单价 " << "商品数量 " <<"单类商品总价 "<< endl;
cart.InitItem(item1);
cart.addItem(item2);
cart.displayCart();
cout << "-------------------------------------------" << endl;
Item item3("notebook", 7.99, 3);
Item item4("Staper", 37.99, 1);
cart.addItem(item3);
cart.addItem(item4);
cart.Changenum("Pen", 3.99, 2);
cart.displayCart();
return 0;
}