【问题标题】:std::cout don't work with overloaded '<<' operator for structstd::cout 不适用于结构的重载 '<<' 运算符
【发布时间】:2020-01-25 11:40:22
【问题描述】:

我已经为 struct LevelStats 实现了 operator '

头文件:

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

这适用于像

这样的操作

文件

,但当用作

std::cout

结果:

错误:无法绑定 'std::ostream {aka std::basic_ostream}' 左值到 'std::basic_ostream&&'

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

【问题讨论】:

  • 将所有出现的ofstream 更改为ostream

标签: c++ struct operator-overloading std


【解决方案1】:

您的operator&lt;&lt; 声明为

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多