0

I am trying to overload the stream insertion operator for an assignment. In my header file, I have the following:

friend ostream& operator<<(ostream, Vector);

In my implementation file, I have:

friend ostream& operator<<(ostream& outputStream, Vector& displayMe) {
    outputStream << "<" << displayMe.GetVX << "," << displayMe.GetVY << ">";
    return outputStream;
}

I am getting an error that says:

"invalid specifier outside a class declaration"

The error is pointing to the line that begins with friend ostream& in my implementation file.

I am new to operator overloading obviously. Am I supposed to define this outside of the class? I am just confused about why I am getting this error and how I go about fixing my code. Any suggestions would be helpful.

  • 1
    See [this](https://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream) – cigien Apr 24 '20 at 22:54
  • You can't use `friend` outside of a class declaration. Also, your definition in your implementation file does not match your declaration in your header file (`ostream` vs `ostream&` in the 1st parameter, and `Vector` vs `Vector&` in the 2nd parameter). The declaration and definition need to match each other. – Remy Lebeau Apr 24 '20 at 23:19

1 Answers1

2

You need to declare the ostream<< operator within the Vector class:

class Vector
{
  // ...
  friend ostream& operator<<(ostream&, Vector&);
};

Notice also that you need to use references in the signature as well.

You don't specify friend in the implementation of the operator.

Also, it's advisable to take the Vector by const-reference here:

ostream& operator<<(ostream&, Vector const&);
cigien
  • 57,834
  • 11
  • 73
  • 112