gpt4 book ai didi

c++ - std::cout 不适用于结构的重载 '<<' 运算符

转载 作者:搜寻专家 更新时间:2023-10-31 01:24:33 25 4
gpt4 key购买 nike

我已经为 struct LevelStats 实现了运算符 '<<' 重载,这似乎适用于 files ,但在与 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&并且不能绑定(bind)到 std::ofstream& .

如果你想输出你的 struct使用 std::cout同时仍然可以使用 std::ofstream , 改变你的 operator<<

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

两者都是 std::ofstreamstd::ostream可以绑定(bind)到 std::ostream &os , 允许你写你的 struct两个文件和std::cout .

关于c++ - std::cout 不适用于结构的重载 '<<' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58095689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com