Operator Overloading in C++ Structs

  c++, c++14, c++17

so I have the following struct:

    struct Item 
{
    string name;
    int iid;
    double value;
    friend istream& operator>>(istream& is, Item& item);
    friend ostream& operator<<(ostream& os, Item& item);
};

Now I would like to overload (cin >>) and (cout <<) in a way that they store & later on print out the elements of a vector<Item> vi;

The vector is going to be initialised from a file 'input.txt'
so:

ifstream file("input.txt");
    Item intake;

    while(file >> intake)
    {
        vi.push_back(intake);
    }

while the output of a vector:

for(i=0;i<vi.size();i++)
    {
        cout << vi[i] << " ";
    }

how can I overload these operators to serve my purpose. In addition, any optimization for my vector initialisation print-out is appreciated.

Thank you in advance!

Source: Windows Questions C++

LEAVE A COMMENT