C++编程逻辑讲解step by step:重载运算符+和-,实现按订单出入库操作。

题目

每按订单发一次货品A,库存都会相应地减少,每次退货,库存都会增加。分别定义货品A库存和订单为两个类:InventoryOrder,库存类Inventory中有货品名称、货品余量属性;订单类Order中有货品名称、数量、总金额属性。

要求重载运算符“-”,实现货品A出库时的库存计算,货品余量减少;重载运算符“+”,实现货品A被退货时的库存计算,货品余量增加。

主函数验证方法:

main()

{

//对例子简化,货品名称为"显示屏"

Inventory inv("显示屏",100);//库存的状态100个显示屏通过构造函数设置

Order order1("显示屏",10,30000);//订单10个显示屏,共30000

Inv= Inv-order1;//出库

inv.display();//显示库存货品和数量

Order order2("显示屏",5,15000);//订单5个显示屏,共15000

Inv= Inv+order1;//退货入库

inv.display();//显示库存货品和数量

}

代码

#include <iostream>
using namespace std;
class StockIn;
class Inventory
{
public:
	Inventory(string ma,int nu,double m, double p);
	Inventory  operator + (StockIn &s);
	void display();

private:
	string name;
	int num;
	double m_avep;
	double price;
};
class StockIn
{
public:
	 StockIn(string a,int b,double c,double p);
	int getinum(){return innum;}
	int geta_price() {return a_price;}
	
private:
	string name;
    int innum;
	double inprice;
	double a_price;
};
Inventory::Inventory(string ma,int nu,double m,double p)
{
	name=ma;//货品余量、移动平均价格、货品金额 
	num=nu;
	m_avep=m;
	price=p;
}
StockIn::StockIn(string a,int b,double c,double p)
{
	name=a;
	innum=b;
	inprice=c;
	a_price=b*c;
}
Inventory Inventory:: operator + (StockIn &s)
{
		
	m_avep= (m_avep * num+s.geta_price())/(num + s.getinum());
	num  = num + s.getinum();
	price=m_avep*num;
	//本次移动平均价= ( 当前库存量* 上次移动平均价+ 本次入库金额) / (当前库存量+ 本次入库量);
	//货品金额= 移动平均价格*货品余量;
	return Inventory(name,num,m_avep,price);
}
void Inventory::display()
{
	cout<<" 货品名称 "<<name<<endl;
	cout<<" 数量 "<<num<<endl;
	cout<<" 移动平均价 "<<m_avep<<endl;
	cout<<" 货品金额 "<<price<<endl;
}

int main()
{
	Inventory inv("显示屏",100,3500,350000);//库存的状态通过构造函数设置,现实中是要读取数据库获取的
	StockIn si("显示屏",10,3000,30000);//本次入库单的数量金额等。
	inv.display();//入库前的库存
	inv=inv+si;
	inv.display();//入库后的库存
	return 0;
}

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值