Search code examples
c++arraysoverridingistream

c++ override the >> operator for Array Class


I'm trying to override the >> operator for my own Array Class:

std::istream& operator>>(std::istream& input, Array& array) {
for (int i = 0; i < array.size; i++)
    input >> array[i];

return input;
}

But i become the following Error:

std::istream& Array::operator>>(std::istream&, const Array&)' must take exactly one argument

All the examples that I've seen, are implemented like it. I don't know, why the compiler want excacty one argument? What have I to do?


Solution

  • If operator>> is a member of the class, it will operate on an Array object and take what parameter you give it:

    Array a;
    a >> whatever;
    

    You seem to want an istream to write into it, which means it's not a member, so either move it outside the class, or declare it as friend (which effectively makes it a non-member):

    class Array
    {
    //.........
    friend std::istream& operator>>(std::istream& input, Array& array) {
       for (int i = 0; i < array.size; i++)
          input >> array[i];
    
       return input;
    }
    };