一个简单的购物车代码,仅支持名字查找删除,一次只能操作购物车里的一个商品
总结:
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(string const name){ goodname = name; } void setPrice(const double p){ price = p; } void setRate(const double r){ rate = r; } }; #endif
//************************************** //版本:简易版2.0 //作者:snowboy //释: //此版本函数一次只操作购物车中的一个商品 //此版本函数仅提供通过商品名字的删除操作 //*************************************** //cart.h #ifndef _CART_H #define _CART_H #include "good.h" #include <vector> #include <iostream> using std::cout; using std::endl; struct item{ //存放商品及其数量 good g; int amount; }; class cart{ private: std::vector<struct item> glist;//订单列表 public: cart(){} void add(good g);//添加商品 void deleteByGoodname(string goodname);//删除商品 double total(); void display();//购物列表展示 double changeTotal();//TODO,改变总价 void changeRateByGoodname(string);//TODO,改变商品折扣率 void changPriceByGoodname(string);//TODO,改变商品价格 }; void cart::add(good g){ std::vector<struct item>::iterator iter=glist.begin(); for(;iter!=glist.end();++iter){ if(iter->g.getGoodname() == g.getGoodname()){ (*iter).amount++; return; } } item t; t.g = g; t.amount = 1; glist.push_back(t); } void cart::deleteByGoodname(string goodname){//按名字删除一个商品 std::vector<struct item>::iterator iter=glist.begin(); for(;iter!=glist.end();++iter){ if(iter->g.getGoodname() == goodname){ iter->amount--; if(iter->amount == 0){ glist.erase(iter); } return; } } cout<<"no this good"<<endl; } void cart::display(){ cout<<"********* good list *********"<<endl; if(glist.size()){ std::vector<struct item>::const_iterator iter=glist.begin(); for(;iter!=glist.end();++iter){ cout<<"goodname: "<<iter->g.getGoodname()<<endl <<"price : "<<iter->g.getPrice()<<endl <<"rate : "<<iter->g.getRate()*100<<"%"<<endl <<"amount : "<<iter->amount<<endl <<"total: : "<<total()<<endl<<endl; } }else{ cout<<"empty list"<<endl<<endl; } } double cart::total(){ if(glist.size()){ std::vector<struct item>::const_iterator iter=glist.begin(); double sum=0.0; for(;iter!=glist.end();++iter){ sum += iter->g.getPrice() * iter->g.getRate() * iter->amount; } return sum; } return 0; } #endif
//test.cpp #include "cart.h" int main() { good g("apple", 76); cart c; c.display(); c.add(g); c.display(); c.add(g); c.display(); c.deleteByGoodname(g.getGoodname()); c.display(); c.deleteByGoodname(g.getGoodname()); c.display(); c.deleteByGoodname(g.getGoodname()); c.display(); c.deleteByGoodname(g.getGoodname()); c.display(); return 0; }