C++ 购物车代码 简易版1.0

一个简单的购物车代码,仅支持名字查找删除,一次只能操作购物车里的一个商品

总结:

1.每5行代码就要进行一下测试

2.基础知识要熟练牢靠

//good.h
#ifndef _GOOD_H
#define _GOOD_H

#include <string>

using std::string;

class good{
	private:
		string goodname; //唯一标识商品
		double price;	 //价格
		double rate;	 //折扣率
	public:
		good(){ //无参构造函数
			goodname = "";
			price = 0.0;
			rate = 1.0;
		}
		good(string s, double p){//无折扣率构造函数
			goodname = s;
			price = p;
			rate = 1.0;
		}
		good(string s, double p, double r){//有折扣率构造函数
			goodname = s;
			price = p;
			rate = r;
		}
		string getGoodname()const {
			return goodname;
		}
		double getPrice()const{
			return price;
		}
		double getRate()const {
			return rate;
		}
		void setGoodname(s
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
购物车管理系统可以使用链表数据结构来实现。每个节点表示一个商品,包含商品信息和指向下一个商品的指针。具体实现可以参考以下代码: ```c++ #include <iostream> #include <string> using namespace std; // 商品类 class Commodity { public: string name; // 商品名称 double price; // 商品价格 int count; // 商品数量 Commodity* next; // 指向下一个商品的指针 // 构造函数 Commodity(string name, double price, int count): name(name), price(price), count(count), next(NULL) {} }; // 购物车类 class ShoppingCart { public: Commodity* head; // 指向购物车中第一个商品的指针 // 构造函数 ShoppingCart(): head(NULL) {} // 添加商品 void addCommodity(string name, double price, int count) { Commodity* commodity = new Commodity(name, price, count); commodity->next = head; head = commodity; } // 删除商品 void removeCommodity(string name) { if (head == NULL) { return; } if (head->name == name) { head = head->next; return; } Commodity* cur = head; while (cur->next != NULL && cur->next->name != name) { cur = cur->next; } if (cur->next != NULL) { Commodity* temp = cur->next; cur->next = temp->next; delete temp; } } // 显示购物车中所有商品 void display() { Commodity* cur = head; while (cur != NULL) { cout << cur->name << " " << cur->price << " " << cur->count << endl; cur = cur->next; } } }; int main() { ShoppingCart cart; cart.addCommodity("apple", 5.0, 2); cart.addCommodity("banana", 3.0, 5); cart.addCommodity("orange", 4.0, 3); cart.removeCommodity("banana"); cart.display(); return 0; } ``` 上面的代码使用链表实现了购物车管理系统。其中,`Commodity`类表示商品,包含了商品的名称、价格、数量和指向下一个商品的指针。`ShoppingCart`类表示购物车,包含了指向购物车中第一个商品的指针,提供了添加、删除和显示商品的方法。在`main`函数中,我们可以看到如何使用购物车管理系统来添加、删除和显示商品。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值