#ifndef ITEMH
#define ITEMH
usingnamespace std;
class Item
{
public:
Item();
Item( int item_id, string desc, double price );
int getId();
string getDescription();
double getPrice();
string toString();
private:
int _item_id;
string _desc;
double _price;
};
#endif
I need to create a class to store the strings created by the Item.h file containing the id, description, and price.
So up till now I created the following .h and .cpp file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#ifndef CONTAINER_H
#define CONTAINER_H
#include "item.h"
class Container
{
public:
Container();
~Container();
void add_item(Item item);
private:
string* _items; //dynamic string since I want to be able to add data as many times as needed
unsignedint _count;
};
#endif
.CPP file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <string>
#include "container.h"
usingnamespace std;
Container::Container(): _items(NULL),_count(0)
{}
Container::~Container()
{
if (_items != (NULL))
{
delete [] _items;
}
}
void Container::add_item(Item item)
{
string*_items += item; // I'm getting an error in this expression
}
I think I'm getting the wrong idea about strings. I thought I could add data just by using '+=' but apparently not .
Please any help
1) I think you are mixing up string and vector. Strings exists to store textual data only. You cannot white some random data in it What you can do: (a) Use a vector<Item>; (b) overload string operator+=(string, Item) to do wht you want; (c) you can define casting Item → string and cast it before assigment.
NOTE: Do not use (b) and (c). I have included them as a reference only!
2) string*_items += item;
You are declaring a new variable _items, which shadows member variable with the same name.
3) string*_items += item;
you are trying to add pointer to string and Item, which doesn't make any sense.
#include "container.h"
Container::Container(){_count=0;}
Container::~Container()
{
if (_items != (NULL))
{
delete [] _items;
}
}
void Container::add_item(Item item)
{
_items[_count]= item;
_count++;
}
void Container::displayitems(int position)
{
for (int i=0, i < _count; i++) // Getting an error here saying 'i' is not a template? and _count does not have a constant value?
}
Seems like there's no need of pointers or vectors, works fine using only strings.
Got a question though, when declaring the constructor how can I set a default value to the _items string?