这是我的示例程序代码。我遇到的问题是,当我向shoppingCart
数组添加新项目时,它会使用当前shoppingCart
生成shoppingindex
数组的新副本。如何将所有这些项添加到同一个shoppingCart
数组中。
#include <iostream>
#include <iomanip>
using namespace std;
class Product{
private:
protected:
static int shoppingindex;
string shoppingcart[10];
public:
Product()
{
}
void displayShoppingCart() const
{
cout << endl<<endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout << " Shopping Cart \n";
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
for(int i=0;i<10;i++)
{
// if(shoppingcart[i].length()<=1)
// {
//
// }
// else
{
cout << "\nShopping Item " <<"("<< i+1 << ")" << " - " << shoppingcart[i] << endl;
//cout << shoppingindex << endl;
}
}
}
};
class DairyProduct:public Product{
private:
protected:
public:
DairyProduct()
{
}
void AddDairyProduct(string productName)
{
shoppingcart[shoppingindex]=productName;
shoppingindex++;
}
};
class Beverages:public Product{
private:
protected:
public:
Beverage()
{
}
void AddBeverage(string productName)
{
shoppingcart[shoppingindex]=productName;
shoppingindex++;
}
};
class PersonalCare:public Product{
private:
protected:
public:
PersonalCare()
{
}
void AddPersonalCare(string productName)
{
//if conditions in all of them to match with the given dataset
shoppingcart[shoppingindex]=productName;
shoppingindex++;
}
};
class ShoppingCart{
public:
Product *object;
DairyProduct *dairy;
Beverages *bevg;
PersonalCare *personal;
ShoppingCart()
{
object = new Product; //deep copy
dairy=new DairyProduct;
bevg=new Beverages;
personal = new PersonalCare;
}
~ShoppingCart()
{
}
};
int Product::shoppingindex=0;
int main()
{
ShoppingCart user;
user.bevg->AddBeverage("Tea");
user.bevg->displayShoppingCart();
user.personal->AddPersonalCare("Shampoo");
user.personal->displayShoppingCart();
user.dairy->AddDairyProduct("Milk");
user.dairy->displayShoppingCart();
}