SomeRandomNick
SomeRandomNick

Reputation: 31

std::cout don't work with overloaded '<<' operator for struct

I've implemented operator '<<' overloading for struct LevelStats , which seems to work well with files , but encounter problem when used with std::cout

header file:

struct LevelStats
{
    DIFFICULTY level;
    std::chrono::duration<double> best_time;
    unsigned int games_played;
    unsigned int games_won;

};

std::ofstream& operator<<(std::ofstream &os, const LevelStats &stats);

cpp file:

std::ofstream &operator<<(std::ofstream &os, const LevelStats &stats) {
    os << static_cast<unsigned int>(stats.level) << " " << "Best_Time= " << stats.best_time.count()<<std::endl;
    os << static_cast<unsigned int>(stats.level) << " " << "Games_Played= " << stats.games_played<<std::endl;
    os << static_cast<unsigned int>(stats.level) << " " << "Games_Won= " << stats.games_won<<std::endl;

    return os;
}

That works well with for operations like

file << LevelStats object

, but when used as

std::cout << LevelStats object

results with :

error: cannot bind 'std::ostream {aka std::basic_ostream}' lvalue to 'std::basic_ostream&&'

Edit: Replaced with std::ostream& meets the same error Another Edit : Dumb mistake in arguments - it works

Upvotes: 2

Views: 561

Answers (1)

Kaldrr
Kaldrr

Reputation: 2850

Your operator<< is declared as

std::ofstream& operator<<(std::ofstream &os, const LevelStats &stats);

Notice that you're passing and returning a reference to std::ofstream. Writing to file will work because you will pass a std::ofstream&, but std::cout is not a std::ofstream& and can not bind to std::ofstream&.

If you want to be able to output your struct using std::cout while still beeing able to use std::ofstream, change your operator<< to

std::ostream& operator<<(std::ostream &os, const LevelStats &stats);

Both std::ofstream and std::ostream can bind to std::ostream &os, allowing you to write your struct to both files and std::cout.

Upvotes: 3

Related Questions