Question

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?

Was it helpful?

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;
}
};

OTHER TIPS

When defined inside the class, binary operator functions should have only one argument (because the left-hand argument is implicitly *this). You have to define the extractor as a free function, which you can do by defining it outside the class. Also, if the extractor needs to access private variables, you can define/declare it as a friend inside the class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top