AmitBL
AmitBL

Reputation: 109

How to overload ofstream operator in c++?

I'm trying to overload an operator so I can write it into a file I created:

typedef struct Square {
    pawn *pawns[2] = { nullptr,nullptr };
}square;

class game {

    player players[2];
    score score1 = 0, score2 = 0;
    square board[10][10];

public:
    //constructor
    friend class ofstream& operator<< (ofstream& out, game curr)
    {
        for (int i = 0; i <= 20; i++)
        {
            out << "=";
        }
        for (int index = 0; index < 10; index++)
        {
            out << '\n';
            for (int j = 0; j <= 10; j++)
            {
                out << "| ";
            }
            out << index << '\n';
            for (int i = 0; i <= 20; i++)
            {
                out << "=";
            }
        }
        out << '\n';
        for (int index = 0; index < 10; index++)
        {
            out << " " << index;
        }
        return(out);
    }

I mainly get Error C2676 :

Severity    Code    Description Project File
Error       C2676   binary '<<': 'ofstream' does not define this operator or a conversion to a type acceptable to the predefined operator

What am I doing wrong?

Upvotes: 1

Views: 8046

Answers (2)

R Sahu
R Sahu

Reputation: 206737

The word class in the line

friend class ofstream& operator<< (ofstream& out, game curr)

is not correct.

Remove that.

Also,

  1. change ofstream to std::ostream so you can use any std::ostream, not just std::ofstream.
  2. Change the second argument type to a const&.

friend std::ostream& operator<< (std::ostream& out, game const& curr)
{
   ...
}

It will be better to move the implementation of the function out of the class definition. It will allow you to implement it in a .cpp file.

For that, I suggest:

// Declare the class
class game;

// Declare the funtion
std::ostream& operator<< (std::ostream& out, game const& curr);

// Make the function a friend of the class.
class game
{
   ...
   friend std::ostream& operator<< (std::ostream& out, game const& curr);
};


// Define the function outside the class definition.
std::ostream& operator<< (std::ostream& out, game const& curr)
{
   ...
}

Upvotes: 2

Peter
Peter

Reputation: 36637

1) Remove class from the line friend class ofstream& operator<< (ofstream& out, game curr).

2) Add an #include <iostream> somewhere above this declaration.

3) Remove using namespace std (since your code is a class definition, which often properly belongs in a header file if you want to use your class types in multiple source files, and using namespace std is bad practice in a header file) and replace all instances of ofstream with std::ostream.

4) (Optional, but good practice). Change the second argument of operator<<() to be a const reference.

Your question was a bit misleading, as the code sample refers to types that are not defined anywhere. In future, provide a MCVE

Upvotes: 2

Related Questions