have the following code that compiles fine as one file, but need to seperate the .cpp files (Item and ShoppingCart) into .cpp and .hpp files. I should end up with 5 files. Item.hpp, Item.cpp, ShoppingCart.hpp, ShoppingCart.cpp, and of course my Main.cpp. I use g++ compiler if that makes a difference. Which #include do i need for each file as well.
//Shopping cart with items
#include <iostream>
using namespace std;
//Item.cpp file
class Item
{
string name;
double price;
int quantity;
public:
//get and set methods
void setName(string nm)
{name=nm;}
string getName()
{return name;}
void setPrice(double pr)
{price=pr;}
double getPrice()
{return price;}
void setQuantity(int qty)
{quantity=qty;}
int getQuantity()
{return quantity;}
//constructor with parameters
Item(string nm,double pr,int qty)
{
name=nm;price=pr;quantity=qty;
}
//ShoppingCart.cpp
class ShoppingCart
{
Item *items[100]; //declare 100 items of pointers
int arrayEnd;//for end of array
public:
ShoppingCart()
{
for(int i=0;i<100;i++) items[i]=NULL; // assign each array element to NULL
arrayEnd=0;
}
void addItem(Item *tItem)
{
items[arrayEnd++]=tItem; //adding each item to array
}
double totalPrice()
{
double total=0;
for(int i=0;i<arrayEnd;i++) //repeat until end of items array
total+=(items[i]->getQuantity()*items[i]->getPrice()); //calling price and quantity by get methods
return total; //return total
}
};
//Main program to for testing your input
int main()
{
Item a("affadavit", 179.99, 12);
Item b("Bildungsroman", 0.7, 20);
Item c("capybara", 4.5, 6);
Item d("dirigible", 0.05, 16);
ShoppingCart sc1;
sc1.addItem(&a);
sc1.addItem(&b);
sc1.addItem(&c);
sc1.addItem(&d);
double diff = sc1.totalPrice();
cout<<"Total price is : "<<diff;
return 0;
}
#include <string>
usingnamespace std;
class Item
{
public:
Item(); //default constructor
//constructor with parameters
Item(string nm,double pr,int qty);
//get and set methods
void setName(string nm);
string getName();
void setPrice(double pr);
double getPrice();
void setQuantity(int qty);
int getQuantity();
private:
string name;
double price;
int quantity;
};
ShoppingCart.hpp:
1 2 3 4 5 6 7 8 9 10 11 12
class ShoppingCart
{
public:
ShoppingCart();
void addItem(Item *tItem);
double totalPrice();
private:
Item *items[100]; //declare 100 items of pointers
int arrayEnd;//for end of array
};
#include "ShoppingCart.hpp"
ShoppingCart::ShoppingCart()
{
for(int i=0;i<100;i++) i
tems[i]=NULL; // assign each array element to NULL
arrayEnd=0;
}
void ShoppingCart::addItem(Item *tItem)
{
items[arrayEnd++]=tItem; //adding each item to array
}
double ShoppingCart::totalPrice()
{
double total=0;
for(int i=0;i<arrayEnd;i++) //repeat until end of items array
total+=(items[i]->getQuantity()*items[i]->getPrice()); //calling price and quantity by get methods
return total; //return total
}