-
That's the same question as you asked before.
You want to add an operator+= to the grocery class. So do it and leave it empty at first. If you get an empty operator+= to compile, then post it here and we can take the next step. First you have to show that you can create the operator, then you can worry about how to implement it.
Secondly, an operator+= takes a value. In this case it will take a products object (or reference). That means that all your code to ask the user for those values must be outside the operator+=, because the += should only be called when you have a products object to insert.
-
yap...you right!
i've created the operator and it's finally working :-)
but can anyone tell me whats the big deal with this?
I had a single function to ask the data from the user and save it into a std::set, now using an operator i have 2 functions, one external function asking the data and on operator saving that data into a std::set :-S
external function:
Code:
void grocery::insertProduct(produts *p)
{
string type, detail, idP;
unsigned int cost, weight;
cout<<"\n Type: ";
getline(cin,type);
...
...
P->setType(type);
...
}
+=operator:
Code:
grocery& grocery::operator += (const products& p)
{
Prod.insert(p);
return *this;
}
-
If you're asking why you should have the operator+= instead of the single insert function from before, then the reason might be because you can call operator+= if you already have a product. For example, right now you are inputting data from the user and adding it to the set. But what if later you want to write code that reads the products from a file and insert them into a set. In that case you can still use your operator+=.
In reality, the real reason is probably that your instructor wants you to learn how to write this kind of operator.
-
The reason you have two different functions is because storing a product has nothing to do with asking the user for information about one. More importantly, the grocery, i.e. what's holding the products, has no business interacting with the user directly. It's just good design.
The reason the insertion is done with the += operator is because your instructor wants you to write one. That part is not necessarily good design. It could have been, if using += to add elements to a collection was common practice in C++, but it isn't.