I have to make class named "Bag" so as this function to be correct
void shopping() {
Bag<string> bag{ "Mike" };
bag= bag + "Apple";
//bag = bag + "Bread" + " Milk";
//bag - "Bread";
bag.printS();
}
Steps that I made:
1)Created a class "Bag" and made a constructor to ensure that "bag" has a name("Mike")
2)I overloaded de "+" operator and here is the first problem: I write list.push_back(n)
(n is a string) and n is put in the "list" but this happens just in that function,how can I make this operation to be visible outside the function?
3)How can I overload a function to make bag + "Bread" + " Milk"
( I don't know how to overload + to make this operation)
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
template<class T>
class Bag {
private:
T name;
vector<T> list;
public:
Bag(T name_) :name{ name_ } {};
T& operator+(T n) {
list.push_back(n);
cout << list.size(); //The result is 1,that means "Apple" is in the bag
return n;
}
void operator-(T n) {
list.erase(list.begin()+1);
}
void printS() {
cout << list.size();
}
};
void shopping() {
Bag<string> bag{ "Mike" };
bag= bag + "Apple";
//bag = bag + "Bread" + " Milk"; //It's commented because it causes an error
//bag - "Bread";
bag.printS(); //Here the result is 0,that means "Apple" is no more in the bag.It's visible only in the function.
}
int main() {
shopping();
int zz;
cin >> zz;
}