1
我有4个类Product和MultiBuyProduct(它是产品的子代),用于计算价格,以及可以添加到MultiBuyProduct的哪些调用函数的购物车获取他们的价格和打印收据控制台,和金额是一个类需要2个整数,并对他们做一些计算,例如添加减去,然后返回格式化的价格。从我的main.cpp我打电话从Child类C++调用基类方法
MultiBuyProduct p2("Wine", Amount(10,0), 2, 10);
ShoppingCart SC;
SC.add(&p2 ,2, true);
下面
显示购物车加入方法
void ShoppingCart::add(Product *p, int quantity, bool end)
{
mProduct = p;
//Sets member vairable value
mQuantity = quantity;
//Gets Name of product 'p'
mProductName = mProduct->getName();
//Gets price of product 'p'
mAmount = mProduct->getPrice();
//Gets total price of product 'p' based on quantity
mAmountTotal = mProduct->getPrice(quantity);
//Updates the GrandTotal
mGrandTotal.add(mProduct->getPrice(0));
}
下面
显示MultiBuyProduct用getPrice
Amount MultiBuyProduct::getPrice(int quantity)
{
if(quantity >= mMinDiscountedQuantity)
{
mPrice.setFullPence(mPrice.getFullPence() * quantity);
mPrice.setPounds(mPrice.getFullPence()/100);
mPrice.setPence(mPrice.getFullPence()%100);
int j = mPrice.getFullPence()/100 * mDiscountedPercent;
saving += j;
int i = mPrice.getFullPence() - j;
mPrice.setFullPence(i);
mPrice.setPounds(i/100);
mPrice.setPence(i%100);
return Amount(mPrice.getFullPence()/100, mPrice.getFullPence()%100);
}
else
{
return Product::getPrice(quantity);
}
}
OK所以基本功能是工作在正确的总打印到控制台,显示10%已被打折,因为数量大于或等于2.
但达到我的else语句(在购物车加入方法寻找项目的单一价格时)
mAmount = mProduct->getPrice();
,但没有返回我认为它是因为某种原因产品不包含数据MultiBuyProduct了,我基本上需要使产品具有与multiBuy产品相同的数据,然后在其上调用get price。 (基本上就像在Java中,我会打电话(否则super.getPrice(数量)< < <,但我知道你不能这样做,在C++)
编辑:这里是
产品类结构:
Product::Product(std::string name, Amount price):aName(name), mPrice(price)
{
}
MultiBuyProduct:
MultiBuyProduct::MultiBuyProduct(std::string aName, Amount price, int minDiscountedQuantity, int discountedPercent)
: mMinDiscountedQuantity(minDiscountedQuantity), mDiscountedPercent(discountedPercent),
mPrice(price), aName(aName)
{
mProduct = Product(mName,mPrice);
}
是啊我认为这是明显的答案,但是当你这样做是编译崩溃becasue aName和mPrice可能尚未初始化 – AngryDuck 2013-03-11 11:25:21
你可以尝试编辑,请回到它是否工作? – Premsuraj 2013-03-11 11:30:11
好吧,以便明显的工作,因为唯一改变的是价格和名称现在在构造函数中初始化,但产品现在甚至没有初始化? – AngryDuck 2013-03-11 11:31:56