我已经为struct LevelStats实现了操作符‘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;
}对于像这样的操作来说,效果很好。
文件<< LevelStats对象
,但当被用作
std::cout << LevelStats对象
成果如下:
错误:无法将'std::ostream {aka std::basic_ostream}‘lvalue绑定到'std::basic_ostream&&’
编辑:替换为std::ostream&遇到了相同的错误,另一个编辑:参数中的愚蠢错误-它可以工作
发布于 2019-09-25 09:57:15
您的operator<<声明为
std::ofstream& operator<<(std::ofstream &os, const LevelStats &stats);注意,您正在传递并返回对std::ofstream的引用。写入文件将工作,因为您将传递一个std::ofstream&,但std::cout不是一个std::ofstream&,不能绑定到std::ofstream&。
如果您希望能够使用struct输出std::cout,同时仍然能够使用std::ofstream,请将operator<<更改为
std::ostream& operator<<(std::ostream &os, const LevelStats &stats);std::ofstream和std::ostream都可以绑定到std::ostream &os,允许您将struct写入文件和std::cout。
https://stackoverflow.com/questions/58095689
复制相似问题