structLevelStatsの演算子 '<<'オーバーロードを実装しました。これはファイルでうまく機能するようですが、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}」左辺値を「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&
。
あなたが出力できるようにしたい場合は、あなたのstruct
使用してstd::cout
、まだ使用することができbeeingている間std::ofstream
、あなたの変更operator<<
には
std::ostream& operator<<(std::ostream &os, const LevelStats &stats);
両方std::ofstream
とstd::ostream
に結合することができstd::ostream &os
、あなたの書き込みすることができ、struct
両方のファイルとしますstd::cout
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加