std::cout 不适用于结构的重载“<<”运算符

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

我已经为 struct LevelStats 实现了运算符“<<”重载,它似乎适用于文件,但在与 std::cout

一起使用时遇到问题

头文件:

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 文件:

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

这适用于

等操作

file << LevelStats object

,但用作

std::cout << LevelStats object

结果:

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

编辑:替换为std::ostream&遇到同样的错误 另一个编辑:参数中的愚蠢错误 - 它有效

您的 operator<< 声明为

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

请注意,您正在传递和返回对 std::ofstream 的引用。 写入文件将起作用,因为您将传递 std::ofstream&,但 std::cout 不是 std::ofstream& 并且无法绑定到 std::ofstream&.

如果您希望能够使用 std::cout 输出您的 struct,同时仍然能够使用 std::ofstream,请将您的 operator<< 更改为

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

std::ofstreamstd::ostream 都可以绑定到 std::ostream &os,允许您将 struct 写入两个文件和 std::cout.