1

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;
}
Ashley
  • 45
  • 5
  • 3
    Your action of `operator +` is inconsistent with the general behavior of that operator. It should return a new `Bag` by value, not modify the existing object and return a `T` reference. I think you're confusing `operator +` with `operator +=`. Likewise for `operator -`. See [What are the basic rules and idioms of operator overloading](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading). – WhozCraig Jul 07 '17 at 16:36
  • I don't exactly know what you are trying to achieve but this is my quick solution: Bag& operator+(const T& n) { list.push_back(n); for (auto i : list) //This for shows me if there is something in the list,and "Apple" is there. cout << i; return *this; } – Kumar Roshan Mehta Jul 07 '17 at 18:16

0 Answers0