c++ - ostream 和 ofstream 运算符重载歧义问题
问题描述
我正在尝试重载 ofstream 和 ostream 运算符,但我遇到了问题。我正在使用 ofstream 保存活动游戏并使用 ostream 在终端上打印。
这是我得到的错误:
hex_game.cpp: In member function ‘void Hex::saveGame(const string&)’:
hex_game.cpp:375:18: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
375 | myfile << (*this);
| ^
hex_game.cpp:193:11: note: candidate 1: ‘std::ofstream& operator<<(std::ofstream&, const Hex&)’
193 | ofstream& operator <<(ofstream& fileOutput, const Hex& obj){
| ^~~~~~~~
hex_game.cpp:207:10: note: candidate 2: ‘std::ostream& operator<<(std::ostream&, Hex&)’
207 | ostream& operator <<(ostream& outputStream, Hex& obj){
第 375 行:
void Hex::saveGame(const string& file_path){
ofstream myfile;
myfile.open(file_path);
myfile << (*this);
cout << "Game has been saved!" << endl;
myfile.close();
}
ostream 的定义 [用于在终端上打印电路板]
ostream& operator <<(ostream& outputStream, Hex& obj){
if(obj.getGameplayType() == 1){
outputStream << "Player1's Score: " << obj.getScoreP1() << " points" << " | Player2's Score: " << obj.getScoreP2() << " points";
}
else{
outputStream << "Player's Score: " << obj.getScoreP1() << " points";
}
outputStream << "\n\n ";
for(int i=0; i<obj.getBoardSize(); i++){
outputStream << " " <<obj.hexCells[0][i].column;
}
outputStream << endl;
for(int i=0; i<obj.getBoardSize(); i++){
outputStream << i + 1;
if(i+1 < 10) outputStream << " ";
if(i >= 1){
for(int j=0; j<i; j++) outputStream << " ";
}
for(int k=0; k<obj.getBoardSize(); k++){
outputStream << " " << obj.hexCells[i][k].point;
}
outputStream << endl;
}
return outputStream;
}
ofstream 的定义 [用于将活动游戏保存到 .TXT 文件中]
ofstream& operator <<(ofstream& fileOutput, const Hex& obj){
fileOutput << obj.getGameplayType() << endl;
fileOutput << obj.getBoardSize() << endl;
fileOutput << obj.getTurn() << endl;
for(int i=0; i<obj.getBoardSize(); i++){
for(int k=0; k<obj.getBoardSize(); k++){
fileOutput << obj.hexCells[i][k].point;
}
fileOutput << endl;
}
return fileOutput;
}
我在网上搜索了我的答案,我得到了一些帮助,但我还没有修复这个错误。我通过在 Hex 构造函数之前添加显式关键字来解决其他歧义问题,但这个不是固定的。有人能帮我吗?
(我必须为 ostream 和 ofstream 重载 <<。这是我的作业,我的同学这样做了,但他们没有收到任何警告。如果有另一种方法(正确),我想学习并在我的代码中实现。)
解决方案
推荐阅读
- android - Android房间使用保存的整数列表/数组来执行sql“IN”查询
- excel - 如何从拆分函数产生的数组创建for循环
- docker - 在 Dockerized create-react-app 中运行“yarn build”时无法识别 SASS_PATH
- sublime-text-plugin - Sublime Text Plugin 打开文件符号
- python - 如何使用python仅删除CSV中的一行
- python - 如何在python中使用多线程并加速代码
- docker - 使用 Osiris Keda 无法扩展 Http 触发器
- node.js - 使用 Heroku 访问本地数据库
- macos - grep 未完成该过程(已杀死:9)
- javascript - SyntaxError:输入 Angular 6 和 RxJS 的意外结束